首页 > 其他 > 详细

[LeetCode] Linked List Cycle II 单链表中的环之二

时间:2014-12-02 14:52:24      阅读:287      评论: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?

 

这个求单链表中的环的起始点是之前那个判断单链表中是否有环的延伸,可参见我之前的一篇文章 (http://www.cnblogs.com/grandyang/p/4137187.html). 还是要设快慢指针,不过这次要记录两个指针相遇的位置,当两个指针相遇了后,让其一指针从链表头开始,一步两步,一步一步似爪牙,似魔鬼的步伐。。。哈哈,打住打住。。。此时再相遇的位置就是链表中环的起始位置。代码如下:

 

/**
 * 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 || !head->next) return NULL;
        ListNode *slow = head;
        ListNode *fast = head;
        while (true) {
            slow = slow->next;
            fast = fast->next;
            if (!fast || !fast->next) return NULL;
            fast = fast->next;
            if (fast == slow) break;
        }
        
        slow = head;
        while (slow != fast) {
            slow = slow->next;
            fast = fast->next;
        }
        return fast;
    }
};

 

单链表中的环的问题还有许多扩展,比如求环的长度,或者是如何解除环等等,可参见网上大神的总结 (http://www.cnblogs.com/hiddenfox/p/3408931.html).

[LeetCode] Linked List Cycle II 单链表中的环之二

原文:http://www.cnblogs.com/grandyang/p/4137302.html

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