您的位置:首页 > 其它

求环的入口结点

2015-10-02 19:47 393 查看
题目描述:

原理:一个链表中包含环,请找出该链表的环的入口结点。

http://blog.sina.com.cn/s/blog_6a0e04380101a9o2.html

/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* MeetingNode(ListNode* pHead)
{  //找到环的入口结点
if(pHead==NULL)
return pHead;
ListNode *s=pHead->next,*f=NULL;
if(s!=NULL)
f=s->next;
while(s!=NULL && f!=NULL)
{
if(s==f)
return f;
s=s->next;
f=f->next;
if(f!=NULL)
f=f->next;
}
return NULL;
}
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if(pHead==NULL)
return pHead;
ListNode* meetNode=MeetingNode(pHead);
if(meetNode==NULL)
return NULL;
ListNode* p=pHead;
while(p!=meetNode)
{
p=p->next;
meetNode=meetNode->next;
}
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: