Skip to content

Commit 542f342

Browse files
committed
added: detect node where cycle begins in LinkedLists
1 parent 4ad8df0 commit 542f342

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

LinkedList/SinglyLinkedList.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,27 @@ private boolean detectLoop() {
271271
return false;
272272
}
273273

274+
// returns node where cycle begins
275+
private ListNode detectCycleNode() {
276+
ListNode fast = head;
277+
ListNode slow = head;
278+
279+
while(fast != null && fast.next != null) {
280+
281+
fast = fast.next.next;
282+
slow = slow.next;
283+
284+
if(fast == slow) {
285+
ListNode current = head;
286+
while(current != slow) {
287+
current = current.next;
288+
slow = slow.next;
289+
}
290+
return slow;
291+
}
292+
}
293+
return null;
294+
}
274295

275296
static boolean compareLists(ListNode head1, ListNode head2) {
276297

0 commit comments

Comments
 (0)