AcWing 34. 链表中环的入口结点-java
原题链接
中等
作者:
jkm
,
2021-03-27 23:39:08
,
所有人可见
,
阅读 264
快慢指针,当两指针相遇时,再另其中一个指针指向头结点,并让两指针以同一速度遍历指针,相遇时必然在入口处
/**
* 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) {
ListNode fast = head, slow = head;
while (fast != null && slow != null) {
slow = slow.next;
fast = fast.next;
if (fast != null)
fast = fast.next;
if (fast == slow) {
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}