首页 > 其他 > 详细

[LeetCode] Linked List Cycle II

时间:2014-06-14 15:49:26      阅读:380      评论: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?

比较直接的方法,时间复杂度O(n^2),指针p每次往下走一步,指针t依次指向head到p之间的结点,判断p->next是不是t,知道p指向末尾结点,或者p->next==t.但提交结果显示 “Time Limit Exceeded”,编程如下:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {

        if(head==NULL)
            return NULL;

        ListNode *p=head,*t;

        while(p!=NULL)
        {
          t = head;
          if(p->next==p)
              return p;
          while(t!=p)
          {
            if(p->next == t)
                return t;
            t = t->next;
          }
          p = p->next;
        }    

    return NULL;
    }//end detectCycle
};//end class

所以要寻求更加简单的方法!看下面龟兔赛跑的故事,明明是数学题好不好,兔子每次跑2个结点,乌龟每次跑1个结点,看下面leetcode讨论中大神stackpop的代码和解释:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* slow = head;
        ListNode* fast = head;
        do{
            if( !slow || !fast ) return NULL;
            slow = slow->next;
            fast = fast->next;
            if( fast ) fast = fast->next;
            else return NULL;
        }while( slow != fast );
        slow = head;
        while( slow != fast ){
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

It is a famous known problem Hare and Tortoise  Length of head to cycle started node:x

Length of the cycle: y

Let hare run two steps while tortoise runs one step

while both of them entered the cycle, the hare is definetly to overlap the tortoise at some node, we define it as m:

The hare totally runs: x + ky + m The tortoise totally runs: x + ty + m Thus, ky = 2ty + x + m we have (x + m) mod y = 0 We can conclude that if the hare run more x steps, it will reach the cycle‘s starting node.

 

[LeetCode] Linked List Cycle II,布布扣,bubuko.com

[LeetCode] Linked List Cycle II

原文:http://www.cnblogs.com/Xylophone/p/3787951.html

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