题目:
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?
/**
* 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 == NULL||head->next==NULL)
return NULL;
else
{
ListNode *slow;
ListNode *quick;
slow = head;
quick = head;
while(quick->next!=NULL && quick->next->next!=NULL)
{
slow=slow->next;
quick=quick->next->next;
if(slow==quick)
break;
}
if(quick->next == NULL || quick->next->next == NULL)
return NULL;
slow = head;
while(slow != quick)
{
slow = slow -> next;
quick = quick-> next;
}
return slow;
}
}
};