The repetitive step in delete a specific node in a Linked List

Viewed 23
//Deletes data given from the linked list
public void deleteByValue(T data) {
    //if empty then simply return
    if (isEmpty())
        return;

    //Start from head node
    Node currentNode = this.headNode;
    Node prevNode = null; //previous node starts from null

    if(currentNode.data.equals(data)) {
        //data is at head so delete from head
        deleteAtHead();
        return;
    }
    //traverse the list searching for the data to delete
    while (currentNode != null) {
        //node to delete is found
        if (data.equals(currentNode.data)){
            prevNode.nextNode = currentNode.nextNode;
            return;
        }
        prevNode = currentNode;
        currentNode = currentNode.nextNode;
    }
}

}

Hi all, I am quite new to data structure and I am confused when I learned how to delete one specific value in the single linked list.

So when we traverse the LinkedList, we have a line like this

prevNode.nextNode = currentNode.nextNode;

I think this already means that we have connected "the previous node before the target node" and "the next node before the current node". Why do we still have these two lines after the traversing of the linked list?

 prevNode = currentNode;
   currentNode = currentNode.nextNode;

Are these two lines mean we are connecting the original previous node with the original next node? I always got lost when the code referred to the "currentNode".How can we tell which is the current "currentNode"?

Could someone help me with this? Visualized answer is appreciated. Thanks so much!

1 Answers

Why do we still have these two lines after the traversing of the linked list?

These are not after traversing; these are the traversing itself.

Some things to note:

  • An assignment to an attribute will mutate the list, like prevNode.nextNode = currentNode.nextNode does.

  • An assignment to a variable will not mutate the list, but can make a reference to a different node, like currentNode = currentNode.nextNode does. This really is the core of traversing: it makes the variable currentNode hop from one node to the next -- without changing anything to the list it is traversing.

  • In this specific algorithm, when the mutation with prevNode.nextNode = currentNode.nextNode is performed, the next thing that happens is a return -- so there is no further traversal happening.

Related