142 Linked List Cycle II

1. Question

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Note:Do not modify the linked list.
Follow up: Can you solve it without using extra space?

2. Implementation

1
/**
2
* Definition for singly-linked list.
3
* class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) {
7
* val = x;
8
* next = null;
9
* }
10
* }
11
*/
12
public class Solution {
13
public ListNode detectCycle(ListNode head) {
14
if (head == null || head.next == null) {
15
return null;
16
}
17
18
ListNode slow = head, fast = head;
19
20
while (fast != null && fast.next != null) {
21
fast = fast.next.next;
22
slow = slow.next;
23
24
if (fast == slow) {
25
break;
26
}
27
}
28
29
if (fast != slow) {
30
return null;
31
}
32
33
slow = head;
34
while (slow != fast) {
35
slow = slow.next;
36
fast = fast.next;
37
}
38
return slow;
39
}
40
}
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)