From 9882f3653750d72a6621b8879855a2c575c6504c Mon Sep 17 00:00:00 2001 From: anebz Date: Mon, 29 Jul 2019 08:12:11 +0200 Subject: [PATCH] 2.3. delete middle node in linked list --- 02. Linked lists/2.3. delete_middle_node.md | 47 +++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 02. Linked lists/2.3. delete_middle_node.md diff --git a/02. Linked lists/2.3. delete_middle_node.md b/02. Linked lists/2.3. delete_middle_node.md new file mode 100644 index 0000000..053d2e8 --- /dev/null +++ b/02. Linked lists/2.3. delete_middle_node.md @@ -0,0 +1,47 @@ +# 2.3. Delete middle node + +## Delete a node in the middle of a singly linked list, given only access to that mode + +* Linked list: a -> b -> c -> d -> e +* Input: c +* Output: nothing, but list looks like this: a -> b -> d -> e + +## 2.3.1. First idea + +In order to delete a node `c`, we need to point `b.next` to `d`. If I only have access to `c`, I have access to c -> d -> e, because it's a singly linked list. There's no way to have information about the previous nodes if I only have `c`. + +## 2.3.2. Hint 1 + +> Picture the list 1 -> 5 -> 9 -> 12. Removing 9 makes the list 1 -> 5 -> 12. Can you make it look like the correct answer? + +I don't get much information from this, each node has 2 attributes: data and next node. When removing 9, we remove the number 9 and point the next node of **5** to 12. But I don't have access to 5. + +What if... I turn 9 into 12, and then delete 12. Of course it would have to run until the end of the list. O(n). + +```java +public void deleteNode(Node c){ + while (c.next != null){ + c.data = c.next.data; + c = c.next; + } + return; +} +``` + +## 2.3.3. Solution + +Copy the data from the next node over to the current node, and then delete the next node. + +```java +public void deleteNode(Node n){ + if (n == null || n.next == null){ + return false; + } + Node next = n.next; + n.data = next.data; + n.next = next.next; + return True; +} +``` + +This is better than my implementation... we don't need to make the data change for all nodes, just the adjacent one. Then we can redirect the next attribute to the node 2 nodes away.