您的位置:首页 > 其它

[LeetCode]Linked List Cycle II

2014-03-14 17:12 281 查看
原题链接:http://oj.leetcode.com/problems/linked-list-cycle-ii/

题意描述:

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?

题解:

  这道题的v1版本是判断一个单链表是否有环,当时我们采用的是快慢指针的方法。传送门:http://www.cnblogs.com/codershell/p/3600100.html

  然而本题有所加强,需要找出环的起点。对于一个存在环的单链表,我们有如下示意图:

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

}
if(q == NULL)
return NULL;

p = head;
while (p != q){
p = p->next;
q = q->next;
}
return q;
}
};


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