首页 > 代码库 > Linked List Cycle

Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

思路:使用两个指针slow和fast,分别以1和2的速度遍历链表。若链表中存在环,则两个指针必然会在某时刻相遇。

 1 class Solution { 2 public: 3     bool hasCycle(ListNode *head) { 4         if( !head || !head->next ) { return false; } 5         ListNode *slow = head, *fast = head; 6         while( fast ) { 7             slow = slow->next; 8             fast = fast->next; 9             if( fast ) { fast = fast->next; }10             if( fast && fast == slow ) { return true; }11         }12         return false;13     }14 };