LeetCode 142: Linked List Cycle II

142. Linked List Cycle II

Difficulty: Medium
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?

思路

首先需要判断链表是否存在环,若存在,假设环有n个结点,定义两个指向链表头结点的指针,其中一个指针先向前移动n步,再两个指针以相同速度向前移动,当两指针相遇时,指向环的入口结点。
接下来的问题是得到环中的结点数,当判断链表是否存在环时,存在环时两指针相遇的结点一定是在环中,可以从该结点向前移动,当回到该结点时,移动步数为环中结点数。判断链表是否有环可以用141题代码,不过函数返回相遇的结点。

代码

[C++]

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *meetingNode = hasCycle(head);
        if (meetingNode == NULL)
            return NULL;
        ListNode *pNode = meetingNode;
        int lenofcycle = 1;
        while (pNode->next != meetingNode) {
            pNode = pNode -> next;
            lenofcycle++;
        }
        ListNode *fast = head;
        ListNode *slow = head;
        for (int i = 0; i < lenofcycle; ++i)
            fast = fast->next;
        while (fast != slow) {
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
    }
    ListNode *hasCycle(ListNode *head) {
        if (head == NULL)
            return NULL;
        struct ListNode *slow = head->next;
        if (slow == NULL)
            return NULL;
        struct ListNode *fast = slow->next;
        while (fast != NULL && slow != NULL) {
            if (fast == slow)
                return fast;
            slow = slow->next;
            fast = fast->next;
            if (fast != NULL)
                fast = fast->next;
        }
        return NULL;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值