题解 | #链表中环的入口结点#
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
这个题是典型的龟兔赛跑。利用快慢指针解决问题
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if(pHead == null || pHead.next == null)return null;//极端情况
if(pHead == pHead.next)return pHead;//只有一个节点的环形链表
ListNode fast = pHead;//快指针
ListNode slow = pHead;//慢指针
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
ListNode slow02 = pHead;
while(slow != slow02){
slow = slow.next;
slow02 = slow02.next;
}
return slow02;//两节点相遇,返回一个即可
}
}
return null;//fast先走出去了就返回空
}
}