双指针应用六:链表的环入口

2021-05-10  本文已影响0人  程一刀

题目地址: https://leetcode-cn.com/problems/linked-list-cycle-ii/

题目描述: 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
参考代码:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *fast = head;
        ListNode *slow = head;
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next;
            fast = fast->next;
            if (slow == fast) {
                ListNode *index1 = head;
                ListNode *index2 = fast;
                while (index1 != index2) {
                    index1 = index1 ->next;
                    index2 = index2 ->next;
                }
                return  index1;
            }
        }
        return nullptr;
        
    }
};

参考链接: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.md

上一篇 下一篇

猜你喜欢

热点阅读