Franz`s blog

快慢指针

快慢指针通常用来解决链表上的环的问题。

思想是fast和slow指针以不同速度移动,fast每次移动两步,slow每次移动一步,如果快指针追上慢指针则说明链表中存在环。也可也用来找链表的中点。

LeetCode 141. 环形链表

本题只要求判断有无环,用最简单的快慢指针即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode slow = head,fast = head.next;
// 如果fast走到null则没有环存在
while(fast != null && fast.next != null && fast != slow){
slow = slow.next;
fast = fast.next.next;
}
return fast == slow;
}
}

LeetCode 142. 环形链表 II

这题难点在于找到入环节点

当快慢指针相遇的时候

head 到 slow的距离 X

环入口到 slow 距离 Y

slow到环入口为 Z

image-20230730153144744

slow走过的距离为 x+y

fast 走过的距离为 x + y + k(z + y)

fast = 2 slow

2(x + y) = x + y + k(z + y)

x = (k - 1)(y + z) + z

因为 y + z为环的长度,所以当走了(k - 1)(y + z)距离时可以看作回到原点,所以 x = z

此时将另外一个指针和慢指针同时每次走一步,相遇的地方就是入环节点。

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
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null || head.next.next == null){
return null;
}
ListNode slow = head.next,fast = head.next.next;
while(fast.next != null && fast.next.next != null && fast != slow){
slow = slow.next;
fast = fast.next.next;
}
if(fast != slow) return null;
fast = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}