美文网首页
[Leetcode] 77. Linked List Cycle

[Leetcode] 77. Linked List Cycle

作者: 时光杂货店 | 来源:发表于2017-03-24 17:02 被阅读5次

    题目

    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?

    解题之法

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

    分析

    这个求单链表中的环的起始点是之前那个判断单链表中是否有环的延伸, 还是要设快慢指针,不过这次要记录两个指针相遇的位置,当两个指针相遇了后,让其一指针从链表头开始,此时再相遇的位置就是链表中环的起始位置。

    详细证明见这篇博客
    关于链表的拓展问题见这篇博客

    相关文章

      网友评论

          本文标题:[Leetcode] 77. Linked List Cycle

          本文链接:https://www.haomeiwen.com/subject/dzyfottx.html