首页 > 其他 > 详细

142. Linked List Cycle II (List; Two-Pointers)

时间:2015-10-03 16:45:11      阅读:108      评论:0      收藏:0      [点我收藏+]

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

思路:设head距离循环开始点k,循环开始点距离fast和slow第一次相遇点x,slow还要走y到达循环开始点。则有:x+y+k=n;  n+x= 2* (k+n); 得到y=k。及相遇点到循环开始点的距离与head到循环开始点的距离相等,那么把slow放到head,fast和slow都用pace=1行走,则在循环开始点两者将相遇。

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* slow = head;  
        ListNode* fast = head;  
        bool flag = false;
          
        while(fast && fast->next) {  
            slow = slow->next;  
            fast = fast->next->next;  
            if(slow == fast)  {
                slow =  head;
                flag = true;
                break;
            }
        } 
        if(!flag) return NULL;
        while(fast!=slow){
            fast = fast->next;
            slow = slow->next;
        }
        return fast;    
    }
};

 

142. Linked List Cycle II (List; Two-Pointers)

原文:http://www.cnblogs.com/qionglouyuyu/p/4853498.html

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