- Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathLinkedListCycleII.java
More file actions
Latest commit
25 lines (25 loc) · 641 Bytes
/
Copy pathLinkedListCycleII.java
File metadata and controls
25 lines (25 loc) · 641 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
/**
* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
*
* <p>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;
}
}