在java中编写从链表中删除特定位置节点的函数时出现空指针异常

在java中编写从链表中删除特定位置节点的函数时出现空指针异常,java,Java,下面是我从链表中删除节点的代码行 Node Delete(Node head, int position) { // Complete this method int pos = 0; Node current = head; Node previous = null; if(position == 0 && head.next == null){ return null; } if(head==null){

下面是我从链表中删除节点的代码行

Node Delete(Node head, int position) {
  // Complete this method
    int pos = 0;
    Node current = head;
    Node previous = null;

    if(position == 0 && head.next == null){
        return null;
    }

    if(head==null){
        return null;
    }

    while(current.next!=null){
        pos = pos + 1;
        current = current.next;
        if(pos==position){
            previous.next = current.next;

        }
        previous = current;

    }
    return head;


}
我目前试图做的是将两个节点声明为current和previous。我将current初始化为链表的head节点,将previous初始化为null。我有两个if语句来处理棘手的情况,比如head为null,而链表中只有一个节点

Node Delete(Node head, int position) {
  // Complete this method
    int pos = 0;
    Node current = head;
    Node previous = null;

    if(position == 0 && head.next == null){
        return null;
    }

    if(head==null){
        return null;
    }

    while(current.next!=null){
        pos = pos + 1;
        current = current.next;
        if(pos==position){
            previous.next = current.next;

        }
        previous = current;

    }
    return head;


}
在while循环中,我有一些代码应该删除位置0以外的节点。对于上面声明的两个节点,我只是通过设置指向当前节点的下一个节点的上一个指针来尝试删除特定位置的节点


然而,它给了我一个空指针异常,我不知道到底是什么出了问题,给了我这样一个错误。非常感谢来自此社区的任何帮助。

请关注其他同行的评论,以便将来进行社区互动

您的问题是在找到位置时没有停止循环:

Node Delete(Node head, int position) {
  // Complete this method
    int pos = 0;
    Node current = head;
    Node previous = null;

    if(position == 0 && head.next == null){
        return null;
    }

    if(head==null){
        return null;
    }

    while(current.next!=null){
        pos = pos + 1;
        current = current.next;
        if(pos==position){
            previous.next = current.next;
            break; // Terminate the Loop
        }
        previous = current;

    }
    return head;
}

欢迎来到堆栈溢出!看起来您需要学习使用调试器。请随便吃点。如果您以后仍然有问题,请随时回来问一个更具体的问题。@Joe C我已经试过使用调试器了。我听说最简单的调试技术是使用我已经尝试过的print语句。从概念上讲,我试图做的是有意义的,然而,问题是我的代码不起作用。所以你可以指出我错的地方。不,我不会。首先,你甚至还没有描述出问题所在。其次,堆栈溢出是一个问答站点,而不是调试服务。如果简单的调试技术不起作用,您将不得不将其提升到一个级别,正如我在提供的链接中详细描述的那样。我仍然会遇到空指针异常。不过谢谢你的帮助。请更加努力并使用调试器!您建议使用哪种调试器@MiguelJet Brain IntelliJ或Eclipse