2.3. delete middle node in linked list

This commit is contained in:
anebz 2019-07-29 08:12:11 +02:00
parent 047db8d544
commit 9882f36537
1 changed files with 47 additions and 0 deletions

View File

@ -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.