|
| 1 | +package com.ctci.linkedlists; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author rampatra |
| 5 | + * @since 2019-02-03 |
| 6 | + */ |
| 7 | +public class LoopDetection { |
| 8 | + |
| 9 | + /** |
| 10 | + * Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. |
| 11 | + * DEFINITION |
| 12 | + * Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so |
| 13 | + * as to make a loop in the linked list. |
| 14 | + * EXAMPLE |
| 15 | + * Input: A -> B -> C -> D -> E -> C [the same C as earlier] |
| 16 | + * Output: C |
| 17 | + * |
| 18 | + * @param head the starting node of the linked list |
| 19 | + * @return the {@code Node} where the loop starts, {@code null} otherwise. |
| 20 | + */ |
| 21 | + private static Node findLoopStartNode(Node head) { |
| 22 | + Node slow = head; |
| 23 | + Node fast = head; |
| 24 | + |
| 25 | + while (fast != null && fast.next != null) { |
| 26 | + slow = slow.next; |
| 27 | + fast = fast.next.next; |
| 28 | + if (slow == fast) { |
| 29 | + break; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /* Error check - no meeting point, and therefore no loop */ |
| 34 | + if (fast == null || fast.next == null) { |
| 35 | + return null; |
| 36 | + } |
| 37 | + |
| 38 | + /* Move slow to Head. Keep fast at Meeting Point. Each are k steps from the |
| 39 | + * Loop Start. If they move at the same pace, they must meet at Loop Start. */ |
| 40 | + slow = head; |
| 41 | + while (slow != fast) { |
| 42 | + slow = slow.next; |
| 43 | + fast = fast.next; |
| 44 | + } |
| 45 | + |
| 46 | + /* You can return either as now both point to the start of the loop */ |
| 47 | + return fast; |
| 48 | + } |
| 49 | + |
| 50 | + public static void main(String[] args) { |
| 51 | + /* |
| 52 | + * 1 -> 2 -> 3 -> 4 -> 5 -> 6 |
| 53 | + * ^ | |
| 54 | + * |_________| |
| 55 | + */ |
| 56 | + Node l1 = new Node(1); |
| 57 | + l1.next = new Node(2); |
| 58 | + l1.next.next = new Node(3); |
| 59 | + l1.next.next.next = new Node(4); |
| 60 | + l1.next.next.next.next = new Node(5); |
| 61 | + l1.next.next.next.next.next = new Node(6); |
| 62 | + l1.next.next.next.next.next.next = l1.next.next.next; |
| 63 | + System.out.println(findLoopStartNode(l1).val); |
| 64 | + } |
| 65 | +} |
0 commit comments