Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
参考了一篇博客:http://www.cnblogs.com/x1957/p/3406448.html
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (!head) return NULL;
ListNode *slow = head, *fast = head;
while (fast) {
if (fast) fast = fast->next;
if (fast) fast = fast->next;
if (slow) slow = slow->next;
if (fast && fast==slow) {
slow = head;
while (slow != fast)
fast = fast->next, slow = slow->next;
return slow;
}
}
return NULL;
}
};