快慢指针(LeetCode 142 Linked List Cycle II)

142. Linked List Cycle II

题目描述:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Notice that you should not modify the linked list.


示例:

Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
在这里插入图片描述
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
在这里插入图片描述
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.


解题思路:(快慢指针)


设快指针和慢指针同时从头结点出发,快指针每次走两步,慢指针每次走一步。当快指针走环形m圈,慢指针走环形n圈后,两指针在紫色点处相遇。

快指针走过的距离: a + m ( b + c ) + b a+m(b+c)+b a+m(b+c)+b

慢指针走过的距离: a + n ( b + c ) + b a+n(b+c)+b a+n(b+c)+b

快指针的速度是慢指针的两倍,所以有: a + m ( b + c ) + b = 2 ∗ [ a + n ( b + c ) + b ] a+m(b+c)+b = 2*[a+n(b+c)+b] a+m(b+c)+b=2[a+n(b+c)+b]

即: a = ( m − 2 n ) ( b + c ) − b = ( m − 2 n − 1 ) ( b + c ) + c a=(m-2n)(b+c)-b=(m-2n-1)(b+c)+c a=(m2n)(b+c)b=(m2n1)(b+c)+c

m − 2 n m-2n m2n为大于等于1的整数

当fast与slow相遇后,fast回到起始位置,slow仍留在第一次相遇的位置,fast与slow都以速度为1前进,第二次相遇点恰好在环的起始位置。(fast到达环的起始位置走过距离为a,此时slow也走了a,b+c 为一圈,slow绕环 m-2n-1 圈后剩下的距离为c,恰好到环的起点处。)


代码:

/**
 * 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) {
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast!=nullptr && fast->next!=nullptr){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow){
               fast = head;
               while(fast != slow){
                   fast = fast->next;
                   slow = slow->next;
               }
               return fast;
            }
        }
        return nullptr;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值