LeetCode 142. 环形链表 II

思路:
快慢指针法:当快指针与慢指针相遇时,分别从起点,相遇点开始走,相遇即为环入口

/**
 * 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* slow = head;
        ListNode* fast = head;

        while (fast && fast ->next) {
            slow = slow ->next;
            fast = fast ->next ->next;

            if (slow == fast) {
                ListNode* index1 = slow;
                ListNode* index2 = head;

                while (index1 != index2) {
                    index1 = index1 ->next;
                    index2 = index2 ->next;
                }

                return index2;
            }

        }

        return NULL;
    }
};
posted @   hjy94wo  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示