-
-
Save jason51122/cafb1093ab8fb82ee0b0 to your computer and use it in GitHub Desktop.
2.6 Given a circular linked list, implement an algorithm which returns the node at the beginning of the loop. DEFINITION Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list. EXAMPLE Input:A ->B->C->D->E-> C[thesameCasearlier] Output:C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ListNode { | |
int val; | |
ListNode next; | |
ListNode(int val) { | |
this.val = val; | |
next = null; | |
} | |
} | |
public ListNode detectCycle(ListNode head) { | |
// Check the edge case when there are only 2 or 3 nodes | |
if (head == null || head.next == null || head.next.next == null) { | |
return null; | |
} | |
ListNode slow = head; | |
ListNode fast = head; | |
while (fast.next != null && fast.next.next != null) { | |
slow = slow.next; | |
fast = fast.next.next; | |
if (slow == fast) { | |
break; | |
} | |
} | |
if (slow != fast) { | |
return null; | |
} | |
slow = head; | |
while (slow != fast) { | |
slow = slow.next; | |
fast = fast.next; | |
} | |
return slow; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment