141. Linked List Cycle
2017-06-21 本文已影响0人
YellowLayne
1.描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
2.分析
快慢指针,慢指针一次走一步,快指针一次走两步。
如果快指针与慢指针相遇,则说明存在环。
3.代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if (NULL == head || NULL == head->next || NULL == head->next->next) return false;
struct ListNode *fast = head->next->next;
struct ListNode *slow = head;
while (fast != slow) {
if (NULL == fast->next || NULL == fast->next->next) return false;
fast = fast->next->next;
slow = slow->next;
}
return true;
}