Pat Pat - 6 months ago 52
Java Question

Linked-List remove after method java

ive been working on a linked list and Im trying to remove a node after another node. Ive got how to remove before the current node but i now need the after and I cant seem to figure it out. I got it to work once but it removed every node after the current not just the one next to the current. Here is the code for inserting after and removing before:

// Remove the node containing item nVal
public void removeBefore(E curVal, E nVal) {
// You implement this method for Assignment 2
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) {

newNode.setNext(curr);
prev.setNext(newNode);
break;
} else {
// advanced curr and prev
prev = null;
curr = curr.getNext();
}
}
}


// Insert new node nVal to the list after current node curVal
public void insertNodeAfter(E nVal, E curVal) {
// You implement this method for Week 11 tutorial
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();
}
}
}


Any guidance is appreciated.

Answer

The code for removing an item containing a given in a singly linked list consists in :

  • search the list from the head for the value, keeping track of previous node
  • if the node is first (previous is null) start the list at next
  • else, make previous point directly to next (also works for last node)

Code could be something like:

// Remove the node containing item nVal
public void remove(E curVal) {
    Node<E> curr = head;
    Node<E> prev = null;


    // scan until locate node or come to end of list
    while (curr != null) {
        // have a match 
        if (curr.getNodeValue().equals(curVal)) {

            if (prev == null) {  // curr is first node: just start to next
                head = curr.getNext();
            }
            else {   // make prev point to next
                prev.setNext(curr.getNext());
            }
            break;
        } else {
            // advanced curr and prev
            prev = curr;
            curr = curr.getNext();
        }
    }
}