|
| 1 | +package main.java.videos; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Map; |
| 8 | + |
| 9 | +/** |
| 10 | + * Code to detect the start of a loop in a linked list. |
| 11 | + * Requested by: Jayadev Senapathi Kota (Hi there!) |
| 12 | + * |
| 13 | + * Run this after removing the package statement above, and specifying the list. |
| 14 | + * |
| 15 | + * Sample Test Case: |
| 16 | + * |
| 17 | + * 1->2->3->4->5->6->3 |
| 18 | + * |
| 19 | + * Output: |
| 20 | + * |
| 21 | + * We should have a loop at 3 |
| 22 | + * We have a loop! Meeting point is: 5 |
| 23 | + * The start of the loop is at 3! |
| 24 | + */ |
| 25 | + |
| 26 | +public class LinkedListWithLoop { |
| 27 | + public static void main(String[] args) throws IOException { |
| 28 | + final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); |
| 29 | + final String nodes[] = bufferedReader.readLine().split("->"); |
| 30 | + final Node start = new Node(Integer.parseInt(nodes[0])); |
| 31 | + Node current = start; |
| 32 | + final Map<Integer, Node> values = new HashMap<>(); |
| 33 | + for (int i = 1; i < nodes.length; i++) { |
| 34 | + final int value = Integer.parseInt(nodes[i]); |
| 35 | + if (values.containsKey(value)) { |
| 36 | + current.next = values.get(value); |
| 37 | + System.out.println("We should have a loop at " + value); |
| 38 | + break; |
| 39 | + } else { |
| 40 | + current.next = new Node(value); |
| 41 | + values.put(value, current.next); |
| 42 | + current = current.next; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + Node hare = start, tortoise = start; |
| 47 | + try { |
| 48 | + do { |
| 49 | + tortoise = tortoise.next; |
| 50 | + hare = hare.next.next; |
| 51 | + } |
| 52 | + while (hare != tortoise); |
| 53 | + System.out.println("We have a loop! Meeting point is: " + hare.value); |
| 54 | + hare = start; |
| 55 | + do { |
| 56 | + tortoise = tortoise.next; |
| 57 | + hare = hare.next; |
| 58 | + } |
| 59 | + while (hare != tortoise); |
| 60 | + System.out.println("The start of the loop is at " + hare.value + "!"); |
| 61 | + } catch (NullPointerException loopNotDetected) { |
| 62 | + System.out.println("I don't see a loop there!"); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | + private static class Node { |
| 68 | + Node next; |
| 69 | + final int value; |
| 70 | + |
| 71 | + public Node(final int value) { |
| 72 | + this.value = value; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | + |
0 commit comments