Leetcode-linked list cycle II

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.