[算法学习]判断链表是否是环结构

问题描述: 判断链表是否是环结构。

解法与分析: 用两个指针的方法判断。

  1. 第一个指针在第一个结点,第二个指针在第二个结点处;
  2. 两个指针同时移动,第一个指针每次移动一个结点,第二个指针每次移动两个结点;
  3. 当第二个指针和第一个指针指向的结点是同一个时,链表有环。

参考代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
static class ListNode
{

int val;
ListNode next;

public ListNode(int val)
{

this.val = val;
}

public ListNode(int val, ListNode next)
{

this.val = val;
this.next = next;
}

@Override
public String toString()
{

return "ListNode [val=" + val + "]";
}
}

/**
* 判断链表是否是环结构
* @param head
* @return
*/

public static boolean isLoop(ListNode head)
{

if(head==null||head.next==null)
{
return false;
}
ListNode pSlow=head;
ListNode pFast=head.next;

while (pFast.next!=null)
{
if(pFast.equals(pSlow))
{
return true;
}
pSlow=pSlow.next;
pFast=pFast.next;
pFast=pFast.next;
if(pFast==null)
{
return false;
}
}
return false;
}