How can one determine whether a singly linked list has a cycle?
第一种方法是从单链表head开始,每遍历一个,就把那个node放在hashset里,走到下一个的时候,把该node放在hashset里查找,如果有相同的,就表示有环,如果走到单链表最后一个node,在hashset里都没有重复的node,就表示没有环。 这种方法需要O(n)的空间和时间。
第二种方法是设置两个指针指向单链表的head, 然后开始遍历,第一个指针走一步,第二个指针走两步,如果没有环,它们会直接走到底,如果有环,这两个指针一定会相遇。
现在找出环的起始位置:
/* (Step 1) Find the meeting point. This algorithm moves two pointers at * different speeds: one moves forward by 1 node, the other by 2. They * must meet (why? Think about two cars driving on a track—the faster car * will always pass the slower one!). If the loop starts k nodes after the * start of the list, they will meet at k nodes from the start of the * loop. */ n1 = n2 = head; while (TRUE) { n1 = n1->next; n2 = n2->next->next; if (n1 == n2) { break; } } // Find the start of the loop. n1 = head; while (n1->next != n2->next) { n1 = n1->next; n2 = n2->next; } Now n2 points to the start of the loop.