首页 > 其他 > 详细

LeetCode:Linked List Cycle II

时间:2014-04-02 13:07:16      阅读:424      评论:0      收藏:0      [点我收藏+]

这道题代码难度并不大,主要是在于怎么想两个快慢指针的运动。

假设轨道长是K1,经过m步,慢指针pslow到达轨道的K2位置与pfast相等。所以得到第一个等式K1+K2=m。(1)

此时pfast跑了2m步,即K1+K2+xl=2m。(l指圈长,x指圈数)。

此时把pfast移到head处,步长改为1,经过K1步,刚到到达环开始处,而此时,pslow从K2经过K1步,经过(1)等式,刚好也在环起始处,此时返回pfast就好了。

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


LeetCode:Linked List Cycle II,布布扣,bubuko.com

LeetCode:Linked List Cycle II

原文:http://blog.csdn.net/whu_sky/article/details/22778327

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!