JZ55-链表中环的入口结点
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
public static ListNode enterNodeOfLoop(ListNode pHead) {
if (pHead == null || pHead.next == null) { //链表为空,或只有一个节点
return null;
}
if (pHead.next == pHead) { //第一个节点就是环
return pHead;
}
HashSet<ListNode> set = new HashSet();
ListNode pCut = pHead;
while (pCut != null) {
if (set.contains(pCut)) {
return pCut;
}
set.add(pCut);
pCut = pCut.next;
}
return null;
}
/**
* 快慢指针 show当前,fast当前的下一个,差1个位置(也可以不差,在同一个起始位置)
* show每次一格,fast每次两格。则n-1(n)次后,fast比show多走一圈
* 还要输出对应的头节点, 数学公式
* 碰头后,快指针返回头节点,然后同步,再次相遇就是环的开始节点
*/
public static ListNode enterNodeOfLoop2(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return null;
}
if (pHead.next == pHead) { //第一个节点就是环
return pHead;
}
ListNode show = pHead;
ListNode fast = pHead;
while (fast != null && fast.next != null) {
show = show.next;
fast = fast.next.next;
if (show == fast) { //有环的情况下
fast = pHead;
while (fast != show) { //可能第一个输入的不是环的入口 9-1-2-3-4-5-3-4-5-3-4-5
show = show.next;
fast = fast.next;
}
return show;
}
}
return null;
}