您的位置:首页 > 其它

Linked List Cycle II

2015-01-09 09:57 204 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.

Follow up:

Can you solve it without using extra space?

这题和上一题不一样,我们要返回圈的初始节点。

首先我们先判断是不是一个环,那么我们可以得到这个环中的一个节点。

那么 我们就能根据这个节点 得到这个环中的节点数。那么就可以像求一个链表中第k个节点一样,用两个指针得到。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *pFirst = head;
ListNode *pSecond = head;
ListNode *pCircle = NULL;
while(pFirst!=NULL&&pSecond!=NULL)
{
pFirst = pFirst->next;
pSecond = pSecond->next;
if(pSecond!=NULL)
pSecond = pSecond->next;
else return NULL;
if(pFirst==pSecond)
{
pCircle = pFirst;
break;
}
}
if(!pCircle) return NULL;
ListNode *pCur = pCircle->next;
int len = 1;
while(pCur!=pCircle)
{
pCur = pCur->next;
len++;
}
pFirst = head;
pSecond = head;
for(int  i =0;i<len;i++)
pSecond = pSecond->next;
while(pFirst!=pSecond)
{
pFirst = pFirst->next;
pSecond = pSecond->next;
}
return pSecond;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: