码迷,mamicode.com
首页 > 其他好文 > 详细

44.Linked List Cycle II(环的入口节点)

时间:2019-06-25 00:18:00      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:int   img   代码   begin   follow   not   integer   思路分析   相等   

Level:

??Medium

题目描述:

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.

技术图片

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.

技术图片

Example 3:

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

技术图片

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

思路分析:

??如果存在环,设置一个快指针,一个慢指针,那么快指针一定会追上慢指针相遇,此时相遇的节点一定在环内,这时可以求出环内节点的数目,然后设置一个前指针和后指针初始值都为head,让前指针先走n次,然后前后指针一起走,如果相等时,则该节点就为环入口节点

代码:

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; //未能相遇则不存在环
    }
}

44.Linked List Cycle II(环的入口节点)

标签:int   img   代码   begin   follow   not   integer   思路分析   相等   

原文地址:https://www.cnblogs.com/yjxyy/p/11080371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!