Created
June 24, 2014 18:02
-
-
Save UncleGarden/7542e36e48a297042df9 to your computer and use it in GitHub Desktop.
CareerCup 150
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
/** | |
* 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 | |
* | |
* @author Jiateng | |
*/ | |
public class CC2_6 { | |
//Time O(n), Space O(1) | |
public static int circleNode(ListNode head) { | |
ListNode fast = head; | |
ListNode slow = head; | |
while (fast != null && fast.getNext() != null) { | |
fast = fast.getNext().getNext(); | |
slow = slow.getNext(); | |
//meet at the start of the circle | |
if (slow == fast) { | |
break; | |
} | |
} | |
//if no meet | |
if (fast == null || fast.getNext() == null) { | |
return 0; | |
} | |
//if meet, change all fast and slow to one step move at one time | |
slow = head; | |
while (slow != fast) { | |
slow = slow.getNext(); | |
fast = fast.getNext(); | |
} | |
return fast.getVal(); | |
} | |
public static void main(String[] args) { | |
//{1-2-3-4-5-3} | |
ListNode head = new ListNode(1); | |
head.next = new ListNode(2); | |
head.next.next = new ListNode(3); | |
head.next.next.next = new ListNode(4); | |
head.next.next.next.next = new ListNode(5); | |
head.next.next.next.next.next = head.next.next; | |
//expect 3 | |
System.out.println(circleNode(head)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment