Question: linked list cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
This question is the follow-up of the linked list loop. To tell the truth, I really didn't think of any better method. I can have an algorithm with a space complexity of O (N), but it's too low to talk about it.
Search for an algorithm that matches the question on the Internet.
Ideas:
1. fast and slow pointers. When we first encounter each other in the ring, we put the fast pointer back at the beginning of the linked list and walked at the speed of each step. When the two pointers met again, it will stop at the starting node of the ring.
Code:
1 # include <stddef. h> 2 3 struct listnode 4 {5 Int val; 6 listnode * Next; 7 listnode (int x): Val (x), next (null) {}; 8 }; 9 10 class solution11 {12 public: 13 listnode * detectcycle (listnode * head) 14 {15 if (! Head) 16 {17 return NULL; 18} 19 20 listnode * One = head; 21 listnode * Two = head; 22 23 while (true) 24 {25 one = one-> next; 26 two = two-> next; 27 if (! Two) 28 {29 return NULL; 30} 31 Two = two-> next; 32 If (! Two) 33 {34 return NULL; 35} 36 // fast and slow pointer encounter, proof that there is a ring 37 If (two = one) 38 {39 two = head; 40 while (two! = One) 41 {42 two = two-> next; 43 One = one-> next; 44} 45 46 Return one; 47} 48} 49} 50 }; 51 52 int main () 53 {54 return 0; 55}View code