forked from mengli/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListCycleII.java
More file actions
Latest commit
28 lines (28 loc) · 604 Bytes
/
Copy pathLinkedListCycleII.java
File metadata and controls
28 lines (28 loc) · 604 Bytes
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
/**
* Given a linked list, return the node where the cycle begins. If there is no
* cycle, return null.
*
* Follow up: Can you solve it without using extra space?
*
*/
publicclassLinkedListCycleII {
publicListNodedetectCycle(ListNodehead) {
if (head == null)
returnhead;
ListNodefast = head, slow = head;
do {
if (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
} else {
returnnull;
}
} while (fast != slow);
slow = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
returnfast;
}
}