简体   繁体   中英

Linked List removing a node from certain position confusion

So lets say we have this linked list: a-> s-> d -> f, and we wanted to remove d.

I'm having trouble understanding why this code below correctly removes an item from the Linked List, and why the code below that doesn't yield the same results?

Correct code:

public void deleteNode(ListNode node) {
    node.val = node.next.val;
    node.next = node.next.next;
 }

Incorrect code:

 public void deleteNode(ListNode node) {
        node = node.next;//d now points to f
        //So wouldn't node s.next now equal f 
        //because we have changed what node d references to? 
 }

Thanks!

The important thing to realize is that the first code doesn't actually "delete the Node 'd'" (like the name would suggest), but instead deletes the value d.

It does so by copying the value from the next node ("f" in your example) to the current node (the node that previously contained "d") and then deletes the next node (the node containing "f"), which is no longer necessary because we have a copy of the value in the current node.

a -> s -> d -> f
a -> s -> f -> f
a -> s -> f

I find that a little bit confusing, I personally would directly delete the node "d", without moving any content around. I guess, it was done that way to better separate node searching and deletion. If you actually wanted to delete a certain node (not its content), you would need a reference to its previous node. That might complicate the interface.

The second code fails precisely because of that problem. It tries to delete the given node - but it can't because deleting it would mean updating the .next member of the previous node, which we don't have access to. The statement in the incorrect code just changes the reference in a local variable, which doesn't have any effect on the actual list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM