力扣 142. 环形链表 II

52 阅读1分钟

🔗 leetcode.cn/problems/li…

题目

  • 给一个链表头,返回链表环的起始起点,若无环返回 nullptr
  • 进阶要求:o(1) 空间复杂度

思路

  • 快慢指针判断环
  • 快慢指针碰到之后,head 未进入环的距离,和慢指针到入环的距离相等

代码

/**
 * 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) {
        if (head == nullptr || head->next == nullptr) return nullptr;
        auto* quick = head->next->next;
        auto* slow = head->next;
        while (quick != nullptr && slow != nullptr) {
            if (quick == slow) break; 
            slow = slow->next;
            quick = quick->next;
            if (quick == nullptr) return nullptr;
            quick = quick->next;
        }
        if (quick == nullptr || slow == nullptr) return nullptr;
        while (head != slow) {
            head = head->next;
            slow = slow->next;
        }
        return head;
        
        
    }
};