<leetcode系列> Linked List Cycle II

Linked List Cycle II

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?

题目大意:
给定一个链表,如果该链表中含有环,则返回这个环开始的那个节点的地址,如果没有环,则返回NULL.

原题链接: https://leetcode.com/problems/linked-list-cycle-ii/

这个题目接Linked List Cycle, 也是快慢指针的运用.示意图如下:
示意图

如上图, 在环的前面,长度为a(即, 从头结点开始,走a步到环的入口), 环的周长为b(即,从环的入口开始,走b步回到入口处).

那么快慢指针每次分别走2步和1步,设走了x步相遇,则:
(2xa)(xa)=nb;n=0,1,2,...

则,可知:
x=nb;n=0,1,2,...

那么,相遇点从环入口处计数,已经走了 nba (步),换句话说, 这个时候再走 a (步)就可以到环的入口处. 如果这个时候再有一个指针,从链表头开始走, 也正好走 a (步) 可以到环入口处.

综上,设快慢指针相遇点为meet, 令一个指针为p, p从头指针出开始走, 每次走一步, meet也跟随p每次走一步.那么他们会在环的入口处相遇.

代码如下:

 // 有环的话,返回快慢指针相遇的地址;
 // 无环的话,返回NULL
 struct ListNode* judgeCycle(struct ListNode *head) {


    int slowStep = 1;
    int fastStep = 2;
    struct ListNode* slow = head;
    struct ListNode* fast = head;
    while (true) {
        for (int j = 0; j < fastStep; ++j) {
            fast = fast->next;
            if (NULL == fast) {
                return NULL;
            }
        }
        for (int i = 0; i < slowStep; ++i) {
            slow = slow->next;
        }
        if (fast == slow) {
            return fast;
        }
    }
}
struct ListNode *detectCycle(struct ListNode *head) {
    if ((NULL == head) || (NULL == head->next)) {
        return NULL;
    }

    struct ListNode* p = head;
    struct ListNode* meet = judgeCycle(head);
    if (NULL == meet) {
        return NULL;
    }

    while (true) {
        if (p == meet) {
            return p;
        }
        p = p->next;
        meet = meet->next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值