简体   繁体   English

从链表中删除节点?

[英]Remove node from linked list?

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.");
        }
        
    }

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.");
        }
        
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM