142 Linked List Cycle II [Leetcode]

44 篇文章 0 订阅

题目内容:

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?

解题思路:
1) 通过一快一慢两个指针,我们可以很方便得检测链表中有没有环,只需不停向前直到两个指针相遇即可。

到达相遇位置后,若让单步走的指针再绕环一圈回到原点,就可以知道环的长度。这时,如果我们让其中一个指针先走环的长度,另一个指针从原点出发,那么他们之后相遇时的位置就是环的入口处。
代码:

/**
 * 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 == NULL || head->next == NULL)
            return NULL;

        ListNode *one = head->next, *two = one->next;

        // check whether there is a cycle in list
        while(two != NULL && one != two) {
            one = one->next;
            two = two->next;
            if(two == NULL)
                break;
            two = two->next;
        }
        if(two == NULL)
            return NULL;

        // get the length of cycle - clength
        int clength(1);
        one = one->next;
        while(one != two) {
            one = one->next;
            ++clength;
        }

        ListNode *p = head;
        one = head;
        for(int i = 0; i < clength; ++i)
            p = p->next;
        while(p != one) {
            p = p->next;
            one = one->next;
        }

        return p;
    }
};

2) 深入分析一下指针在查找环过程中的相遇点:

设链表开始处距离环入口处的距离为k,环的长度为c。

当慢指针到达入口处时,它走了k步,而快指针此时已经在环内,一共走了2k步,设此时它距离环的入口n步。那么还需要c-n步,快指针就会和慢指针相遇(快指针每次都赶上慢指针一步)。相遇时的位置就是c-n(慢指针是从环的入口处出发的)。

再考察k与c、n之间的关系。快指针在圈内从起点开始行走了k步到达了n的位置,那么它们之间的关系满足: k=cx+n ,x为自然数。

如果从相遇时的位置开始,让慢指针再走 cx+n 步,就会又回到入口处的节点。显然k满足条件。因此我们重新设置一个指针指向起始节点,让起始节点的指针和环中慢节点的指针同时向前走k步,这两个指针必然在环的入口处相遇。

实现代码:

/**
 * 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 == NULL || head->next == NULL)
            return NULL;

        ListNode *one = head->next, *two = one->next;

        // check whether there is a cycle in list
        while(two != NULL && one != two) {
            one = one->next;
            two = two->next;
            if(two == NULL)
                break;
            two = two->next;
        }
        if(two == NULL)
            return NULL;

        ListNode *p = head;
        while(p != one) {
            p = p->next;
            one = one->next;
        }

        return p;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值