# 【LeetCode】142. Linked List Cycle II 解题报告（Python & C++）

900 篇文章 155 订阅
1033 篇文章 56 订阅

id： fuxuemingzhu

## 题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.


Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.


Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.


• Can you solve it without using extra space?

## 解题方法

### 双指针

1. 首先要证明的是，两指针相遇时，慢指针还没有走完整个链表。

• 当慢指针没走完一圈时，显然成立
• 假设慢指针走完了一圈之后相遇，可以假定快指针在O的前一个位置，慢指针走一圈回到了O点，此时快指针走了两圈又回到了O的前一个位置，所以在慢指针走玩一圈之前就已经相遇。
2. 快慢指针在x处第一次汇合，xo之间距离为x，假如快指针走了n圈，快指针走过的路程为a+x+n*(c + x)，慢指针走过的路程为a+x，所以a+x+n*(c + x) = 2(a+x),所以a + x = n*(c + x)，也就是SOx之间的距离等于n圈的长度，所以令慢指针从起点开始一次一步，快指针从x开始顺时针方向转也一次一步，同时前进，则慢指针走a时，快指针走了n*(c+x) - x的长度，则必会在O处相遇！

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if not fast or not fast.next:
return None
while slow != fast:
slow = slow.next
fast = fast.next
return fast


C++代码如下：

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if (slow == fast)
break;
}
if (!fast || !fast->next || slow != fast) return nullptr;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
};


### set

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
visited = set()
return None


/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
unordered_set<ListNode*> visited;
}
return nullptr;
}
};


## 日期

2018 年 3 月 12 日
2019 年 1 月 11 日 —— 小光棍节？

• 1
点赞
• 0
收藏
• 打赏
• 4
评论
06-05 389
07-15 27
09-07 103

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。