Skip to content

Commit 3bb8137

Browse files
committed
Linked List Cycle II
1 parent c98dabb commit 3bb8137

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

LinkedListCycleII.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Given a linked list, return the node where the cycle begins. If there is no
3+
* cycle, return null.
4+
*
5+
* Follow up: Can you solve it without using extra space?
6+
*
7+
*/
8+
public class LinkedListCycleII {
9+
public ListNode detectCycle(ListNode head) {
10+
if (head == null)
11+
return head;
12+
ListNode fast = head, slow = head;
13+
do {
14+
if (fast.next != null && fast.next.next != null) {
15+
fast = fast.next.next;
16+
slow = slow.next;
17+
} else {
18+
return null;
19+
}
20+
} while (fast != slow);
21+
slow = head;
22+
while (fast != slow) {
23+
fast = fast.next;
24+
slow = slow.next;
25+
}
26+
return fast;
27+
}
28+
}

0 commit comments

Comments
 (0)