题解 | #链表中环的入口结点#
链表中环的入口结点
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,就可以判断了。

查看30道真题和解析