[Leetcode] Linked List Cycle II single-linked list of rings in the second

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?

The starting point of the ring in the single-linked list is the extension of the previous single-linked list to see if there is a ring in it, as in one of my previous articles (http://www.cnblogs.com/grandyang/p/4137187.html). Or to set a fast and slow pointer, but this time to record two pointers to meet the position, when two pointers meet, let its a pointer from the list Head Start, Step Two step, step by step like Minion, like the Devil's pace ... Haha, hold on. At this point the location of the link is the beginning of the ring in the list. The code is as follows:

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*detectcycle (ListNode *head) {        if(!head | |!head->next)returnNULL; ListNode*slow =Head; ListNode*fast =Head;  while(true) {Slow= slow->Next; Fast= fast->Next; if(!fast | |!fast->next)returnNULL; Fast= fast->Next; if(Fast = = slow) Break; } Slow=Head;  while(Slow! =fast) {Slow= slow->Next; Fast= fast->Next; }        returnFast; }};

There are many extensions to the ring problem in a single-linked list, such as the length of the loop, or how to remove the ring, and so on, see the summary of the online deity (http://www.cnblogs.com/hiddenfox/p/3408931.html).

[Leetcode] Linked List Cycle II single-linked list of rings in the second

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.