Leetcode Linked List Cycle II

Source: Internet
Author: User

Leetcode Linked List Cycle II

 

 

Linked List Cycle IITotal Accepted: 20444 Total Submissions: 66195My Submissions

 

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?


 

 


A single-chain table is given to determine whether a ring exists in the linked list. If so, the node starting with the ring is returned.
Ideas:
1. Define two pointers. The fast pointer fast takes two steps at a time. The slow pointer s takes one step at a time. If they meet at a non-tail node, the loop exists.
2. if a ring exists and the circumference of the ring is set to r, when the encounter occurs, the slow pointer takes the slow step, the fast pointer takes the 2 s step, and the fast pointer has gone through the n ring in the ring,
Then there is an equation 2 s = s + nr and s = nr
3. When encountering each other, set another slow pointer slow2 to go forward from the beginning of the linked list. Because s = nr, the two slow pointers will meet at the starting point of the ring.
Complexity: time O (n)

struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *detectCycle(ListNode *head) {if(!head || !head->next) return NULL;ListNode *fast, *slow, *slow2;fast = slow = slow2 = head;while(fast && fast->next){fast = fast->next->next;slow = slow->next;if(fast == slow && fast != NULL){while(slow->next){if(slow == slow2){return slow;}slow = slow->next;slow2 = slow2->next;}}}return NULL;}


 

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.