AcWing 34. 链表中环的入口结点
原题链接
中等
作者:
小轩喵灬
,
2025-01-10 15:14:03
,
所有人可见
,
阅读 2
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
public ListNode entryNodeOfLoop(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
do {
fast = fast.next.next;
slow = slow.next;
if (fast == null || fast.next == null) {
return null;
}
} while(fast != slow);
fast = head;
while(fast != slow) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}