题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
分析:
1.设订两个指针,pFast和pSlow,pFast每次走两个结点,pSlow每次一个结点
2.如果有环,pFast和pSlow相遇一定是在环内
3.相遇以后,pSlow不动,pFast回到头结点.
4.pFast和pSlow一起走,每次都走一个结点
5.当pFast和pSlow再次相遇的时候就是入口.
算法推倒:
C++代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if(pHead == NULL || pHead->next == NULL || pHead->next->next == NULL)
return NULL;
ListNode* p2 = pHead->next->next; //因为后面是p2!=p1所以不能从头结点开始
ListNode* p1 = pHead->next;
while(p2 != p1)
{
if(p2 != NULL || p2->next != NULL)
{
p2 = p2->next->next;
p1 = p1->next;
}
else
{
return NULL;
}
}
p2 = pHead;
while(p1 != p2)
{
p2 = p2->next;
p1 = p1->next;
}
return p2;
}
};
python代码:
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
pFast = pHead
pSlow = pHead
while pFast != None and pFast.next != None:
pFast = pFast.next.next
pSlow = pSlow.next
if pFast == pSlow:
break
if pFast == None or pFast.next == None:
return None
pFast = pHead
while pFast != pSlow:
pFast = pFast.next
pSlow = pSlow.next
return pFast