简体   繁体   中英

What does this code do specifically? And how can I change it?

public void deleteAfter(Node prev){
    prev.setNext(prev.next().next());
}

This method deletes the new node after the given prev node. Could someone explain to me what this code does specifically step by step and how I can change it so that it won't error if prev is the last node on the list.

@param prev - The node before the place where it will be inserted.

prev.next().next() gets the node after the next node (from the one given). That's then passed to the prev.setNext method, making it the next node. That essentially removes the node in between prev and the next next node.

Basically, it takes prev -> next_1 -> next_2 ... and turns it into prev -> next_2 ...

If prev is the last node in the list, then next() should return null (I assume). If that's the case, you can do a null check to avoid an error.

public void deleteAfter(Node prev){
    if(prev.next() != null) {
        prev.setNext(prev.next().next());
    }
}

The code sets a new next such that if you had a -> b -> c , now you'll have a -> c .

To avoid the error, you can check if next returns null, or maybe invoke hasNext if such a method exists on Node.

if(prev.next() != null){
  ...
}

It unlinks the link between the node before the node to be deleted and then links the node before the node to be deleted to the node after the node to be deleted.

在此输入图像描述

You have some Node, somewhere in a list. I've highlighted it.

... - node - node - (prev) - node - node - ...

The first call, is to set the "prev"'s next link prev.setNext(...) but what is that next going to be set to? It will be set to "next's next" or (staring with prev)

... - node - node - (prev) - node - node - ...

The prev.next() would be

... - node - node - prev - (node) - node - ...

And the prev.next().next() would be

... - node - node - prev - node - (node) - ...

So, after the setting operation, your arrangement would look like

... - node - node - prev  node--node - ...
                        \------/

Note that the prev's new "next node" was previously prev's next, next node.

If you ever ask yourself "What is this code doing????", there is an excellent chance that the code can be written in a more descriptive way. For example:

public void deleteNodeAfter(Node index) {
    // Borrowed from Bill the Lizard's answer
    if (index.next() != null) {
        index.setNext(index.next().next());
    }
}

To answer you directly: This code deletes a node from a linked 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