码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List Cycle II

时间:2015-03-16 12:38:20      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

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?

思路:1.在检测有没有环时,记录第一次相遇的点。 2.另p1=node first met,p2=node from the start. 然后just walk one step each time, 当p1与p2相遇时,即找到圆的起点。

这个思路有木有很diao!!(申明不是我想的)哈哈哈,leetcode下面的神评论把我笑死了!

技术分享 

 

/**
 * 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 *p1,*p2;
        p1=p2=head;
        bool isCycled=false;
        while(p1 && p2 && p2->next){
            p1=p1->next;
            p2=p2->next->next;
            if(p1==p2) {isCycled=true;break;}
        }
        p2=head;
        while(isCycled){
            if(p2==p1) return p1;
            p2=p2->next;
            p1=p1->next;
        }
        return NULL;
    }
};

 

Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/renrenbinbin/p/4341366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!