linked-list-cycle-ii

本文介绍了一种高效算法来解决链表中有环的问题,即如何找到环的起始节点。通过快慢指针法首先确定环的存在,接着计算环内的节点数量,最后巧妙地利用两个指针以特定速度前进,最终在环的入口节点相遇。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

剑指offer里也有同样的题,分为三步找到环形链表的入口结点,这里就只记录这次自己写的代码,具体的思路分析见链表中环的入口结点

代码:

/**
 * 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 *meetingnode = meetingcycle(head);
        if(meetingnode==NULL)
            return NULL;

        //计算环内节点个数
        int count = 1;
        ListNode *cur = meetingnode;
        while(cur!=NULL){
            cur = cur->next;            
            if(cur==meetingnode)
                break;
            count++;//这里要注意break和count++的顺序问题
        }

        //寻找入口点
        ListNode *slow = head;
        ListNode *fast = head;
        for(int i = 0;i < count;++i){
            fast = fast->next;
        }
        while(slow!=fast){
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }

    //找到一个环内节点
    ListNode *meetingcycle(ListNode *head){
        if(head==NULL || head->next==NULL)
            return NULL;
        ListNode *slow = head;
        ListNode *fast = head->next;
        while(slow!=NULL && fast!=NULL){
            if(slow==fast)
                return slow;
            slow = slow->next;
            fast = fast->next;
            if(fast!=NULL)
                fast = fast->next;
        }
        return NULL;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值