[LeetCode] Linked List Cycle II

Source: Internet
Author: User

[LeetCode] 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?

First, set the ring length to r. When the distance from the ring port to a is met, and the distance from the outer ring is B, there is 2 (a + B) = a + B + nr, n> 1;

So there is a + B = nr; Further there are B + pr = (r-a) + qr, that is, the pointer from the beginning and the pointer from the current encounter position must move at the same speed at the ring port position.

 

 

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {public ListNode detectCycle(ListNode head) {if(head==null) return null;ListNode slow2 = head;ListNode slow = head;ListNode fast = head;boolean isCycle = false;while(fast!=null&&fast.next!=null){slow = slow.next;fast = fast.next.next;if(slow == fast) {isCycle =  true;break;}}if(isCycle){while(slow2!=slow){slow = slow.next;slow2 = slow2.next;}return slow;}else{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.