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?
Hide TagsLinked List Pointers began to make two a point, using the Val of node as a judge, in fact, based on memory judgment. Find the starting position of the chain ring, this painting slowly find the law can: thinking:
- Use the fast pointer, the slow pointer each time before the further, the quick pointer every two steps
- If the quick and slow hands meet, then move the fast pointer from the tag with the linked header to the previous
- When the fast and slow hands meet again is the ring start position.
This realization, the time quickly o (n), and the Space O (1)
#include <iostream>using namespacestd;/** * Definition for singly-linked list.*/structListNode {intVal; ListNode*Next; ListNode (intx): Val (x), Next (NULL) {}};classSolution { Public: ListNode*detectcycle (ListNode *head) { if(Head==null)returnNULL; ListNode* fast=head,*slow=Head; while(1){ if(fast->next!=null) fast=fast->Next; Else returnNULL; if(fast->next!=null) fast=fast->Next; Else returnNULL; Slow=slow->Next; if(Fast==slow) Break; } Fast=Head; while(1){ if(Fast==slow)returnslow; Fast=fast->Next; Slow=slow->Next; } returnNULL; }};intMain () {ListNode Node1 (1), Node2 (2), Node3 (3), Node4 (4), NODE5 (5); Node1.next=&Node2; Node2.next=&Node3; Node3.next=&Node4; Node4.next=&Node5; Node5.next=&Node1; Solution Sol; ListNode*ret = Sol.detectcycle (&Node1); if(ret==null) cout<<"NULL"<<Endl; Elsecout<<ret->val<<Endl; return 0;}View Code
[Leetcode] Linked list cycle II chain ring start position