您的位置:首页 > 其它

leetcode - Linked List Cycle II

2015-07-14 17:53 489 查看
leetcode - 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?

/**
* 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(NULL == head || NULL == head->next) return NULL;
ListNode *p1 = head->next;
ListNode *p2 = head->next->next;
while(p2 != NULL && p2->next != NULL && p1 != p2){
p1 = p1->next;
p2 = p2->next->next;
}
if(p1 == p2){
ListNode *tp = head;
while(tp != p2){
tp=tp->next;
p2=p2->next;
}
return tp;
}
else return NULL;
}
};


两个指针ptr1和ptr2,都从链表头开始走,ptr1每次走一步,ptr2每次走两步,等两个指针重合时,就说明有环,否则没有。如果有环的话,那么让ptr1指向链表头,ptr2不动,两个指针每次都走一步,当它们重合时,所指向的节点就是环开始的节点。
http://blog.sina.com.cn/s/blog_6f611c300101fs1l.html#cmt_3246993
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: