题目链接

LeetCode

题目描述

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos-1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

说明: 不允许修改给定的链表。

进阶:

  • 你是否可以使用 O(1) 空间解决此题?

示例 1:

142. 环形链表 II - 图1

输入: head = [3,2,0,-4], pos = 1
输出: 返回索引为 1 的链表节点
解释: 链表中有一个环,其尾部连接到第二个节点。

示例 2:

142. 环形链表 II - 图2

输入: head = [1,2], pos = 0
输出: 返回索引为 0 的链表节点
解释: 链表中有一个环,其尾部连接到第一个节点。

示例 3:

142. 环形链表 II - 图3

输入: head = [1], pos = -1
输出: 返回 null
解释: 链表中没有环。

提示:

  • 链表中节点的数目范围在范围 [0, 104]
  • -105 <= Node.val <= 105
  • pos 的值为 -1 或者链表中的一个有效索引

    解题思路

    方法一:哈希表

    1. class Solution {
    2. public:
    3. ListNode *detectCycle(ListNode *head) {
    4. unordered_set<ListNode *> visited;
    5. while (head != nullptr) {
    6. if (visited.count(head)) {
    7. return head;
    8. }
    9. visited.insert(head);
    10. head = head->next;
    11. }
    12. return nullptr;
    13. }
    14. };
  • 时间复杂度 O(n)

  • 空间复杂度 O(n)

    方法二:快慢指针

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode *detectCycle(ListNode *head) {
  12. if(head==NULL||head->next==NULL){
  13. return NULL;
  14. }
  15. ListNode* slow = head;
  16. ListNode* fast = head;
  17. do{
  18. fast = fast->next->next;
  19. slow = slow->next;
  20. }while(fast&&fast->next&&fast!=slow);
  21. if(fast == NULL){
  22. return NULL;
  23. }
  24. fast = head;
  25. while(fast&&slow&&fast!=slow){
  26. fast = fast->next;
  27. slow = slow->next;
  28. }
  29. if(fast == slow){
  30. return fast;
  31. }
  32. return NULL;
  33. }
  34. };
  • 时间复杂度 O(n)
  • 空间复杂度 O(1)