Description:
Given a linked list, determine if it has a cycle in it.
Example:
Given -21->10->4->5, tail connects to node index 1, return true
Link:
[http://www.lintcode.com/en/problem/linked-list-cycle/]
解题思路:
设定快慢指针,fast一次走两步,slow一次走一步,如果fast || fast->next == NULL则没有cycle,如果fast == slow 则存在循环。
Tips:
有两个指针,所以题目开始要查head和head->next是否为空。
在快慢指针跑起来以后,只要有循环那么一定会碰面,只要没有循环那么快指针肯定先到终点。
Time Complexity:
O(n)
完整代码:
bool hasCycle(ListNode *head) { if(head == NULL || head->next == NULL) return false; ListNode* fast; ListNode* slow; slow = head; fast = head->next; while(slow != fast) { if(fast == NULL || fast->next == NULL) return false; slow = slow->next; fast = fast->next->next; } return true; }