- 题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
- 分析
判断环的入口点问题用快慢指针来解决:
代码:
/*
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 || pHead.next.next == null){
return null;
}
ListNode fast = pHead.next.next;
ListNode slow = pHead.next;
//先判断链表有没有环
while(fast != slow){
if(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}else{
return null;
}
}
slow = pHead;
while(fast != slow){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}