您的位置:首页 > 其它

leetcode刷题日记—— Linked List Cycle II

2015-12-31 12:21 288 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:

Can you solve it without using extra space?

问题分析:这个题目和之前的题目类似,都是判断是否是循环链表。并返回节点。但是这里要求不能够改变链表。所以之前的那种方式不再适用。这里采用双指针的方式,一个指针的移动速度是另外一个指针的二倍,如果存在循环,必然会出现相遇。但是注意相遇的节点不一定是最开始连上的那个节点。实现代码如下:

/**
* 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) {
if(head==NULL) return NULL;
if(head->next==NULL) return NULL;
ListNode *p=head,*q=head,*m=NULL;
while(p&&q->next){
p=p->next;
q=q->next->next;
if(q==NULL) return NULL;
if(p==q)
{
q= head;
while(q!=p)
{
p= p->next;
q= q->next;
}
m= p;
break;
}

}
return m;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: