|
| 1 | +// Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e. any node but the first and last node, |
| 2 | +// not necessarily the exact middle) of a singly linked list, given only access to that node. |
| 3 | +// EXAMPLE: |
| 4 | +// Input: the node c from the linked list a => b => c => d => e => f |
| 5 | +// Result: nothing is returned, but the new linked list looks like a => b => d => e => f |
| 6 | + |
| 7 | +const assert = require("assert"); |
| 8 | + |
| 9 | +class LinkedListNode { |
| 10 | + constructor(val, next) { |
| 11 | + this.val = val === undefined ? null : val; |
| 12 | + this.next = next === undefined ? null : next; |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +const arrayToLinkedList = (arr) => { |
| 17 | + let tail = null; |
| 18 | + for (let i = arr.length - 1; i >= 0; i--) { |
| 19 | + tail = new LinkedListNode(arr[i], tail); |
| 20 | + } |
| 21 | + return tail; |
| 22 | +}; |
| 23 | + |
| 24 | +const compareLinkedLists = (A, B) => { |
| 25 | + if (!A && !B) return true; |
| 26 | + |
| 27 | + while (A !== null && B !== null) { |
| 28 | + if (A.val !== B.val) return false; |
| 29 | + A = A.next; |
| 30 | + B = B.next; |
| 31 | + } |
| 32 | + return !A && !B; |
| 33 | +}; |
| 34 | +/** |
| 35 | + * Deletes an inputted node somewhere in the middle of the linked list |
| 36 | + * @param {LinkedListNode} node input node to be removed |
| 37 | + * @return {null} |
| 38 | + * |
| 39 | + * There's no trick to this problem. We know that a linked list, fundamentally, is just a collection of nodes with |
| 40 | + * values that point to another node. We don't need to necessarily delete the selected node. We just need to overwrite |
| 41 | + * what that node represents. In other words, we can overwrite the next node onto the current node, then skip from the |
| 42 | + * current node to the next next node, effectively skipping over the node after the selected node since it's redundant. |
| 43 | + * Runtime: O(1) |
| 44 | + * Space: O(1) |
| 45 | + * |
| 46 | + */ |
| 47 | +const deleteMiddleNode = (node) => { |
| 48 | + // It is safe to assume from the prompt that the given node exists in the linked list and is not the head nor tail |
| 49 | + const next = node.next; |
| 50 | + node.val = next.val; |
| 51 | + node.next = next.next; |
| 52 | +}; |
| 53 | + |
| 54 | +describe(module.filename, () => { |
| 55 | + it("should remove a node in the middle of the linked list", () => { |
| 56 | + const arr = [1, 2, 3, 4, 5]; |
| 57 | + let ll1 = arrayToLinkedList(arr); |
| 58 | + const nodeToBeRemoved = ll1.next.next.next; |
| 59 | + const expectedArr = [1, 2, 3, 5]; |
| 60 | + let expectedLL1 = arrayToLinkedList(expectedArr); |
| 61 | + |
| 62 | + deleteMiddleNode(nodeToBeRemoved); |
| 63 | + |
| 64 | + assert.ok(compareLinkedLists(ll1, expectedLL1)); |
| 65 | + }); |
| 66 | +}); |
0 commit comments