LeetCode 142 :Linked List Cycle II

问题描述

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.

思路同https://blog.csdn.net/weixin_44135282/article/details/102731012

(1)第一步是确定一个链表中是否包含环。我们可以用两个指针来解决这个问题。定义两个指针pfast和pslow,同时从链表的头结点head出发,pslow一次走一步,pfast一次走两步。
如果pfast追上了pslow(pfast == pslow),那么链表就包含环;pfast走到了链表的末尾都没有追上pslow,那么链表就不包含环。

(2)第二步是确定环中节点的数目,当pfast == pslow时,假设pslow走过x个节点,则pfast走过2x个节点。设环中有n个节点,因为pfast比pslow多走一圈(n个节点),
所以有等式2x = n + x,可以推出n = x,即pslow走了一个环的步数n

(3)第三步是找到环的入口。当pfast == pslow时,pslow走了一个环的步数n,即Pslow先在链表上向前移动一个环的步数n步,pslow的位置不变,pfast重新指向链表头部head
,然后pslow和pfast一起向前每次走一步 (速度相同),直到pfast == pslow(相遇),此时两个指针相遇的节点就是环的入口
(pslow指向环的入口节点时,pslow已经围绕着环走了一圈,又回到了入口节点,因为pslow先走了一个环的步数)
在这里插入图片描述

java实现

/**
 * 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 || head.next==null || head.next.next==null)
            return null;
        ListNode pslow=head.next;
        ListNode pfast=head.next.next;
        int num=0;
        while (pfast!=null && pfast.next!=null){
            if(pfast==pslow){//说明有环
                pfast=head;//pfast重新指向链表头部head
                while (pfast!=pslow){
                    pfast=pfast.next;
                    pslow=pslow.next;
                }
                return pfast;//pfast == pslow,此时两个指针相遇的节点就是环的入口
            }
            pslow=pslow.next;
            pfast=pfast.next.next;
        }
        return null;
    }
}
发布了172 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44135282/article/details/103449902