题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

import java.util.*;
/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        ListNode fast = pHead;
        ListNode slow = pHead;
        if(fast.next==null){return null;}
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                fast=pHead;
                while(slow != fast){
                
                fast=fast.next;
                slow=slow.next;
                }return slow;
            }
        }

        return fast;
    }
}

寻找链表中的环的入口,现根据快慢指针能否重合判断环是否存在,再将其中一个放到开头,两个以慢指针速度行走,重合处就是环的入口,要额外注意的就是{},{1}型与{1},{},根据phead.next是否可能是null,就可以判断了。

全部评论

相关推荐

牛至超人:您好,京东物流岗了解一下吗?负责精加工食品的端到端传输
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务