Skip to content

Instantly share code, notes, and snippets.

@jason51122
Created July 2, 2014 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jason51122/cafb1093ab8fb82ee0b0 to your computer and use it in GitHub Desktop.
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
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