44.Linked List Cycle II (entry node ring)

Level:

  Medium

Subject description:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

img

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

img

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

img

Follow up:
Can you solve it without using extra space?

Analysis of ideas:

  If the presence of a ring, provided a quick pointer, a pointer is slow, then the pointer will soon overtake slow pointer met, then the node must meet in the ring, then the number of ring nodes may be determined and set a pointer to the front and after the initial pointer values ​​are head, so that the front pointer go n times, then go back and forth together with the pointer, if equal, the entry node to ring node

Code:

public class Solution{
    public ListNode detectCycle(ListNode head){
        ListNode meetNode=meetNoding(head);
        if(meetNode==null)
            return null;
        ListNode pNode=meetNode;
        int count=1;
        while(pNode.next!=meetNode){
            count++;
            pNode=pNode.next;
        }
        ListNode slow=head;
        ListNode fast=head;
        for(int i=0;i<count;i++){
            slow=slow.next;
        }
        while(fast!=slow){
            fast=fast.next;
            slow=slow.next;
        }
        return fast;
    }
    //求相遇的节点
    public ListNode meetNoding(ListNode head){
        if(head==null)
            return null;
        if(head.next==null)
            return null;
        ListNode slow=head.next;
        ListNode fast=slow.next;
        while(slow!=null&&fast!=null){
            if(slow==fast)
                return fast;
            slow=slow.next;
            fast=fast.next;
           if(fast!=null&&fast.next!=null)
               fast=fast.next; //快指针一次走两步
        }
        return null; //未能相遇则不存在环
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11080371.html