Skip to content

Commit 03fddb9

Browse files
committed
链表环问题:判断环,求相遇点...
1 parent 351a9d4 commit 03fddb9

5 files changed

+89
-6
lines changed

Tests/CMakeLists.txt

Lines changed: 0 additions & 6 deletions
This file was deleted.

leetcode_solved/[editing]leetcode_0141_Linked_List_Cycle.cpp

Whitespace-only changes.

leetcode_solved/[editing]leetcode_0142_Linked_List_Cycle_II.cpp

Whitespace-only changes.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* AC: Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.
3+
* Memory Usage: 39.8 MB, less than 69.19% of Java online submissions for Linked List Cycle.
4+
*
5+
* 思路:快慢指针法, T:O(n), S:O(1), n 为链表长度
6+
*/
7+
/**
8+
* Definition for singly-linked list.
9+
* class ListNode {
10+
* int val;
11+
* ListNode next;
12+
* ListNode(int x) {
13+
* val = x;
14+
* next = null;
15+
* }
16+
* }
17+
*/
18+
public class Solution {
19+
public boolean hasCycle(ListNode head) {
20+
// 长度0,1情况
21+
if (head == null || head.next == null) {
22+
return false;
23+
}
24+
25+
ListNode fasterPointer = head;
26+
while (head != null) {
27+
head = head.next;
28+
if (fasterPointer == null) {
29+
return false;
30+
}
31+
fasterPointer = fasterPointer.next;
32+
if (fasterPointer == null) {
33+
return false;
34+
}
35+
fasterPointer = fasterPointer.next;
36+
if (head == fasterPointer) {
37+
return true;
38+
}
39+
}
40+
41+
return false;
42+
}
43+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* AC: Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle II.
3+
* Memory Usage: 38.9 MB, less than 81.24% of Java online submissions for Linked List Cycle II.
4+
*
5+
* 思路:快慢指针法。 细节的是需要证明当快慢两指针相遇时,慢指针再走一倍已走过的路程,最终会停在环处。
6+
* 复杂度:T:O(n), S:O(s)
7+
*/
8+
/**
9+
* Definition for singly-linked list.
10+
* class ListNode {
11+
* int val;
12+
* ListNode next;
13+
* ListNode(int x) {
14+
* val = x;
15+
* next = null;
16+
* }
17+
* }
18+
*/
19+
public class Solution {
20+
public ListNode detectCycle(ListNode head) {
21+
// 坑:注意链表 length >= 0,单独处理0的情况,否则 fasterPointer.next 抛空指针异常
22+
if (head == null) {
23+
return head;
24+
}
25+
26+
ListNode slowerPointer = head, fasterPointer = head;
27+
while (fasterPointer.next != null && fasterPointer.next.next != null) {
28+
slowerPointer = slowerPointer.next;
29+
fasterPointer = fasterPointer.next.next;
30+
// 有环
31+
// 快慢指针相遇
32+
if (slowerPointer == fasterPointer) {
33+
// 设置第二个慢指针,从链表头开始。可以证明第二个慢指针与第一个慢指针会在链表的环处相遇。
34+
ListNode tempPointer = head;
35+
while (slowerPointer != tempPointer) {
36+
slowerPointer = slowerPointer.next;
37+
tempPointer = tempPointer.next;
38+
}
39+
return slowerPointer;
40+
}
41+
}
42+
43+
// 无环
44+
return fasterPointer.next == null ? fasterPointer.next : fasterPointer.next.next;
45+
}
46+
}

0 commit comments

Comments
 (0)