题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
public class Solution {
public ListNode hasCycle(ListNode head) {
//先判断链表为空的情况 fast-template
if (head == null)
return null;
//快慢双指针
ListNode fast = head;
ListNode slow = head;
//如果没环快指针会先到链表尾
while (fast != null && fast.next != null) {
//快指针移动两步
fast = fast.next.next;
//慢指针移动一步
slow = slow.next;
//相遇则有环,返回相遇的位置
if (fast == slow)
return slow;
}
//到末尾说明没有环,返回null
return null;
}
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode slow = hasCycle(pHead);
//没有环
if (slow == null)
return null;
//快指针回到表头
ListNode fast = pHead;
//再次相遇即是环入口
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}

上海得物信息集团有限公司公司福利 1166人发布