码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Linked List Cycle II

时间:2017-06-19 19:43:03      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:runtime   append   this   post   lis   break   turn   for   begin   

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?

解题思路

设链表长度为n,头结点与循环节点之间的长度为k。定义两个指针slow和fast,slow每次走一步,fast每次走两步。当两个指针相遇时,有:

  • fast = slow * 2
  • fast - slow = (n - k)的倍数
    由上述两个式子能够得到slow为(n-k)的倍数

两个指针相遇后,slow指针回到头结点的位置,fast指针保持在相遇的节点。此时它们距离循环节点的距离都为k,然后以步长为1遍历链表,再次相遇点即为循环节点的位置。

实现代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

 //Runtime:16 ms
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (head == NULL)
        {
            return NULL;
        }

        ListNode *slow = head;
        ListNode *fast = head;
        while (fast->next && fast->next->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if (fast == slow)
            {
                break;
            }
        }

        if (fast->next && fast->next->next)
        {
            slow = head;
            while (slow != fast)
            {
                slow = slow->next;
                fast = fast->next;
            }

            return slow;
        }

        return NULL;
    }
};

[LeetCode] Linked List Cycle II

标签:runtime   append   this   post   lis   break   turn   for   begin   

原文地址:http://www.cnblogs.com/blfbuaa/p/7049933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!