转载自gaofen100博客园,感谢作者整理!

How can one determine whether a singly linked list has a cycle?

第一种方法是从单链表head开始,每遍历一个,就把那个node放在hashset里,走到下一个的时候,把该node放在hashset里查找,如果有相同的,就表示有环,如果走到单链表最后一个node,在hashset里都没有重复的node,就表示没有环。 这种方法需要O(n)的空间和时间。

 

第二种方法是设置两个指针指向单链表的head, 然后开始遍历,第一个指针走一步,第二个指针走两步,如果没有环,它们会直接走到底,如果有环,这两个指针一定会相遇。

 

现在找出环的起始位置:

Cpp代码 
 1 /* (Step 1) Find the meeting point. This algorithm moves two pointers at  
 2 * different speeds: one moves forward by 1 node, the other by 2. They  
 3 * must meet (why? Think about two cars driving on a track—the faster car  
 4 * will always pass the slower one!). If the loop starts k nodes after the  
 5 * start of the list, they will meet at k nodes from the start of the  
 6 * loop. */  
 7 n1 = n2 = head;   
 8 while (TRUE) {   
 9     n1 = n1->next;   
10     n2 = n2->next->next;   
11     if (n1 == n2) {   
12         break;   
13     }   
14 }   
15 // Find the start of the loop.   
16 n1 = head;   
17 while (n1->next != n2->next) {   
18     n1 = n1->next;   
19     n2 = n2->next;   
20 }   
21 Now n2 points to the start of the loop.