diff --git a/02. Linked lists/2.7. intersection.java b/02. Linked lists/2.7. intersection.java new file mode 100644 index 0000000..274695f --- /dev/null +++ b/02. Linked lists/2.7. intersection.java @@ -0,0 +1,44 @@ +public static LinkedListNode intersect(LinkedListNode a, LinkedListNode b){ + + if (a == null || b == null) return null; + + LinkedListNode a_head = a; + LinkedListNode b_head = b; + int a_len, b_len = 1; + + // iterate through A + while (a_head.next != null){ + a_head = a_head.next; + a_len += 1; + } + + // iterate through B + while (b_head.next != null){ + b_head = b_head.next; + b_len += 1; + } + + // last node inequal, return null + if (a_head != b_head) return null; // changed from before + + // compare lengths, adjust node + if (a_len == 1 or b_len == 1) return a_head; + + // improved + LinkedListNode shorter = a_len < b_len ? a : b; + LinkedListNode longer = b_len < a_len ? b : a; + int diff = Math.abs(a_len - b_len); + + while(k > 0 && longer != null){ + longer = longer.next; + k--; + } + + // there's intersection + while(shorter != longer){ + shorter = shorter.next; + longer = longer.next; + } + + return shorter; +} \ No newline at end of file diff --git a/02. Linked lists/2.7. intersection.md b/02. Linked lists/2.7. intersection.md index c8213cd..2d0451b 100644 --- a/02. Linked lists/2.7. intersection.md +++ b/02. Linked lists/2.7. intersection.md @@ -249,54 +249,4 @@ Takeaways: * When comparing nodes, compare `a == b`, not `a.data == b.data` * Get a new class for the tail and lengths -Improved algorithm: - -```java - -public static LinkedListNode intersect(LinkedListNode a, LinkedListNode b){ - - if (a == null || b == null) return null; - - LinkedListNode a_head = a; - LinkedListNode b_head = b; - int a_len, b_len = 1; - - // iterate through A - while (a_head.next != null){ - a_head = a_head.next; - a_len += 1; - } - - // iterate through B - while (b_head.next != null){ - b_head = b_head.next; - b_len += 1; - } - - // last node inequal, return null - if (a_head != b_head) return null; // changed from before - - // compare lengths, adjust node - if (a_len == 1 or b_len == 1) return a_head; - - // improved - LinkedListNode shorter = a_len < b_len ? a : b; - LinkedListNode longer = b_len < a_len ? b : a; - int diff = Math.abs(a_len - b_len); - - while(k > 0 && longer != null){ - longer = longer.next; - k--; - } - - // there's intersection - while(shorter != longer){ - shorter = shorter.next; - longer = longer.next; - } - - return shorter; -} -``` - -Because we're comparing by reference not value, the condition in `while` won't be met if two nodes have the same `.data` but different `.next`. +Improved algorithm in **2.7. intersection.java**. Because we're comparing by reference not value, the condition in `while` won't be met if two nodes have the same `.data` but different `.next`.