一个链表中包含环,请找出该链表的环的入口结点。
/*
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) {
return null;
}
ListNode pSlow = pHead;
ListNode pFast = pHead;
do {
if (pFast.next == null) {
return null; // 有空值说明改链表没有环
}
pSlow = pSlow.next;
pFast = pFast.next;
if (pFast.next == null) {
return null; // 有空值说明改链表没有环
}
pFast = pFast.next;
} while (pSlow != pFast);
pSlow = pHead;
while (pSlow != pFast) {
pSlow = pSlow.next;
pFast = pFast.next;
}
return pSlow;
}
}
原文:http://www.cnblogs.com/rosending/p/5693155.html