[Leetcode] Linked list cycle II chain ring start position

Source: Internet
Author: User

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:
    1. Use the fast pointer, the slow pointer each time before the further, the quick pointer every two steps
    2. If the quick and slow hands meet, then move the fast pointer from the tag with the linked header to the previous
    3. 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

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.