首页 > 其他 > 详细

Leetcode: Linked List Cycle II

时间:2014-11-25 16:22:04      阅读:270      评论: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?

分析:类似于linked list cycle I,用两个pointer,一个每个step往后移一个,另一个每个step往后移两个。当两个指针相交时,快指针走过的路程恰好是慢指针走过的路程的两倍,则我们可以得到:从链表头到环开始点的距离等于从两指针相交点到环开始点的距离(next方向)。那么我们让slow指针继续走,fast指针从head开始往后走(每个step后移一个),当fast和slow重合时即为环开始点。代码如下:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == NULL || head->next == NULL) return NULL;
        
        ListNode *slow = head, *fast = head;
        //find meeting point
        while(slow->next && fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast) break;
        }
        //no cycle
        if(slow != fast) return NULL;
        //find cycle beginning
        fast = head;
        while(fast != slow){
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
    }
};

 

Leetcode: Linked List Cycle II

原文:http://www.cnblogs.com/Kai-Xing/p/4121074.html

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