题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
  public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        // 空的情况
        if (pHead == nullptr) return nullptr;

        // 双指针法 快慢指针
        ListNode* pSlow = pHead;
        ListNode* pFast = pHead;
        while(1){

            // 移动不同的长度
            pSlow = pSlow->next;
            pFast = pFast->next->next;
            if(pFast == nullptr || pSlow == nullptr){
                break;
            }

            // 有环的话快指针会追上慢指针
            if (pSlow == pFast) {
                // 追上了 开始找环的入口
                pSlow = pHead;
                while (pSlow != pFast) {
                    pSlow = pSlow->next;
                    pFast = pFast->next;
                }
                return pSlow;
            }
        }
        return nullptr;

    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
10-10 00:14
门头沟学院 Java
程序员小白条:20年架构师,无工资
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务