Home > OS >  Remove node from linked list?
Remove node from linked list?

Time:08-14

I am trying to remove a node from a linked list but I am having trouble, I get this error:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "List.Node.getNext()" because "this.cursor" is null
    at List/List.List.removeNode(List.java:34)
    at List/List.Main.main(Main.java:10)

Here is the code for the node:

package List;

public class Node <T>{
    private T data;
    private Node<T> next;
    
    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }
    
    public T getData() {
        return data;
    }
    
    public void setNext(Node<T> next){
        this.next = next;
    }
    public Node<T> getNext() {
        return next;
    }
}

This is the method I am using to remove the node:

public void removeNode(T data) {
        cursor = head;
        
        while(cursor!=null || cursor.getNext().getData()!=data) {
            cursor = cursor.getNext();
        }
        if(cursor!=null) {
            cursor.setNext(cursor.getNext().getNext());
        }else {
            System.out.println("Could not find node.");
        }
        
    }

CodePudding user response:

Removing node in linked list is tricky, there are different cases:

  1. Removing first node: you just set linked list root to next node
  2. Removing not first node is just as you implemented -- you set previous node next node to next node of deleted node.

Hope it helps!

public void removeNode(T data) {
        var cursor = head;
        Node<T> prev = null;

        while (cursor != null && cursor.getData() != data) {
            prev = cursor;
            cursor = cursor.getNext();
        }

        if (cursor != null) {
            if (prev == null)
               root = cursor.getNext();
            else
               prev.setNext(cursor.getNext());
        } else {
            System.out.println("Could not find node.");
        }
        
    }
  • Related