Pat Pat - 6 months ago 30
Java Question

LinkedList insert After node

I've been trying to insert a node into a linked list after the current node using Java. I've been able to get the insertion before the current node but I cannot get this to work:

Here is the code for

insertNodeBefore
. I just want to know if there is a way to adapt this to be able to insert after the current node?

// Insert new node nVal to the list before current node curVal
public void insertNodeBefore(E nVal, E curVal) {
Node<E> newNode = new Node<E>(nVal);

Node<E> curr = head;
Node<E> prev = null;

if (head.getNodeValue() == curVal) {
newNode.setNext(head);
head = newNode;
return;
}

// scan until locate node or come to end of list
while (curr != null) {
// have a match
if (curr.getNodeValue() == curVal) {
// insert node
newNode.setNext(curr);
prev.setNext(newNode);
break;
} else {
// advanced curr and prev
prev = curr;
curr = curr.getNext();
}
}
}

Answer

Basically find the node and then:

  • set the next of new node equals to the current
  • set the next of the current to the new node

Something like this should work:

public void insertNodeBeAfter(E nVal, E curVal) {
    Node<E> newNode = new Node<E>(nVal);

    Node<E> curr = head;

    // scan until locate node or come to end of list
    while (curr != null) {
        // have a match 
        // Replaced == with .equals
        if (curr.getNodeValue().equals(curVal)) {
            // insert node
            newNode.setNext(curr.getNext());
            curr.setNext(newNode);
            break;
        } else {
            curr = curr.getNext();
        }
    }
}

Note is not necessary to have a different treatement for the head because it doesn't change.