【剑指Offer | C++ 】面试题23:链表中环的入口节点

该文章介绍了一种使用快慢指针算法来找到链表中环的入口节点的方法。首先,通过快慢指针定位环内的节点,然后计算环的长度,最后让一个指针从头节点开始,另一个指针在环内按长度移动,两者相遇点即为环的入口。

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

题目:
如果一个链表中包含环,设计一个函数找出环的入口节点。

解题思路:

  • 快慢指针 -> 定位环内节点
  • 定义辅助节点得到环的长度k
  • 节点1从头先走k次,节点2出发,相遇点即为环的入口点

代码:

#include "pch.h"
#include<iostream>
using namespace std;

struct ListNode {
    int value;
    ListNode* next;
};


ListNode* RingNode(ListNode* Node) {
    if (Node == nullptr) return nullptr;
    
    ListNode* pSlow = Node;
    ListNode* pFast = Node;

    while (!(pFast->next == nullptr || pFast->next->next == nullptr)) {
        
        pSlow = pSlow->next;
        pFast = pFast->next->next;
        if (pSlow == pFast)return pSlow;

    }
    return nullptr;
    

}

int RingLen(ListNode* Node) {
    if (Node == nullptr)return 0;
    int len = 1;
    ListNode* tmp = Node->next;
    while (tmp != Node) {
        len++;
        tmp = tmp->next;
    }
    return len;
}

ListNode* findEntance(ListNode* node, int len) {
    if (len == 0 || node == nullptr )return nullptr;
    ListNode* preNode = node;
    for (int i = 0; i < len; i++) {
        preNode = preNode->next;
    }

    ListNode* res = node;
    while (res != preNode) {
        res = res->next;
        preNode = preNode->next;
    }
    return res;
}

int main()
{
    ListNode* p1 = new ListNode();
    p1->value = 4;
    
    ListNode* p2 = new ListNode();
    p2->value = 3;
    p2->next = p1;
    ListNode* p3 = new ListNode();
    p3->value = 2;
    p3->next = p2;
    ListNode* p4 = new ListNode();
    p4->value = 1;
    p4->next = p3;

    p1->next = p3;

    ListNode* ringNode = RingNode(p4);
    
    int len = RingLen(ringNode);
    ListNode* entrance = findEntance(p4, len);
    //cout << entrance->value;
}

注意代码的防御性!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赛文X

觉得不错就打赏下呗mua~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值