|
| 1 | +public class LinkedListAlgorithms { |
| 2 | + /** |
| 3 | + * Detects the cycle, if exists, in a given linked list, using Floyd's |
| 4 | + * turtoise and hare algorithm, or two-pointer technique. |
| 5 | + * |
| 6 | + * <p> |
| 7 | + * Runs in O(n) time and O(1) memory. |
| 8 | + * |
| 9 | + * @param list |
| 10 | + * @return The first node in the cycle. |
| 11 | + */ |
| 12 | + public static <T> LinkedListNode<T> detectCycle(LinkedList<T> list) { |
| 13 | + LinkedListNode<T> rabbit = list.getHead(); |
| 14 | + LinkedListNode<T> turtle = list.getHead(); |
| 15 | + |
| 16 | + while (rabbit != null && rabbit.next != null) { |
| 17 | + rabbit = rabbit.next.next; |
| 18 | + turtle = turtle.next; |
| 19 | + |
| 20 | + if (rabbit == turtle) { |
| 21 | + LinkedListNode<T> bear = list.getHead(); |
| 22 | + |
| 23 | + while (bear != rabbit) { |
| 24 | + bear = bear.next; |
| 25 | + rabbit = rabbit.next; |
| 26 | + } |
| 27 | + |
| 28 | + return bear; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return null; |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Returns the intersection of two linked lists. |
| 37 | + * |
| 38 | + * <p> |
| 39 | + * Given lists A and B, first starts at the head of list B and travels to the |
| 40 | + * end (the last node after the intersection), which we call <code>tail</code>. |
| 41 | + * Then routes tail to A's head to form a cycle. Proceeds to use Floyd's |
| 42 | + * turtoise and hare algorithm starting from B's head. |
| 43 | + * |
| 44 | + * <p> |
| 45 | + * Runs in linear time and constant memory. |
| 46 | + * |
| 47 | + * @param listA |
| 48 | + * @param listB |
| 49 | + * @return The intersection of two given lists, or <code>null</code> if there |
| 50 | + * is no intersection. |
| 51 | + */ |
| 52 | + public static <T> LinkedListNode<T> getIntersection(LinkedList<T> listA, LinkedList<T> listB) { |
| 53 | + LinkedListNode<T> tail = listB.getHead(); // The last node after the intersection (if exists) |
| 54 | + |
| 55 | + while (tail.next != null) |
| 56 | + tail = tail.next; |
| 57 | + |
| 58 | + tail.next = listA.getHead(); |
| 59 | + LinkedListNode<T> intersection = detectCycle(listB); |
| 60 | + |
| 61 | + tail.next = null; |
| 62 | + return intersection; |
| 63 | + } |
| 64 | +} |
0 commit comments