Fork me on GitHub

leetcode——[142]Linked List Cycle II环形链表 II

题目

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos-1,则在该链表中没有环。

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

示例 1:

1
2
3
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。

img

示例 2:

1
2
3
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。

img

示例 3:

1
2
3
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。

img

进阶:
你是否可以不用额外空间解决此题?

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:

1
2
3
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.

img

Example 2:

1
2
3
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.

img

Example 3:

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

img

Follow up:
Can you solve it without using extra space?

解题方法

先使用快慢指针fastslow判断链表是否有环,无环返回Null

有环,假设链表起点为H环的入口节点为I,快慢指针相遇节点为MHI的距离为aIM的距离为b,环的长度为l

快指针fast比慢指针slow多跑一圈,即a+b=l。又因为环入口I到相遇节点M的距离为b,所以相遇节点M到环入口I的距离也为a,即链表起点H到环入口节点I的距离。(建议画下图很容易看出来)

所以此时快指针fast和链表起点p同时出发,相遇节点即环入口节点。这段代码跑了1ms,超过了98.32%的Java提交。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
// Method 1 1ms 98.32%
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode fast = head.next;
ListNode slow = head;
ListNode p = head;
while(fast != null && fast != slow) {
slow = slow.next;
fast = fast.next;
if (fast != null) {
fast = fast.next;
}
}
if (fast != null) {
fast = fast.next;
while(fast != p) {
fast = fast.next;
p = p.next;
}
}
return fast;
}
}
BJTU-HXS wechat
海内存知己,天涯若比邻。