链表在排序链表中插入一个节点



>强调文本 我需要传递链表的标题和要插入该链表的数据。假设列表按排序顺序排列,我需要检查每个节点的数据并插入新节点以给出新的排序列表。

得到空指针异常,,我需要知道我做错了什么

/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
     Node prev;
  }
*/
Node SortedInsert(Node head,int data) {
    Node root= head;
    if(head==null){
        root.data=data;
        root.next=null;
        root.prev=null;
    }else if(head.data>data){
            Node newnode = new Node();
           newnode.data=data;
           newnode.next=head;
           newnode.prev=null;
            head.prev=newnode;
            root=newnode;
        }
    int k=0;
    while(head!=null && k==0){
        if(head.data<data && head.next.data>data && head.next!=null){
           Node temp=head.next;
           Node newnode = new Node();
           newnode.data=data;
           newnode.next=temp;
           newnode.prev=head;
           head.next=newnode;
           temp.prev=newnode;k++; break;
       }
        else if(head.data<data && head.next==null){
           //Node temp=head.next;
           Node newnode = new Node();
           newnode.data=data;
           newnode.next=null;
           newnode.prev=head;
           head.next=newnode;k++;break;
           //temp.prev=newnode;
       }else 
       {head=head.next;}
    }
  return root;
}

IM 在循环中的第二个 if 语句处获得空指针异常。

我发现您的代码中有一些错误,可能会给NullPointerException 所以相应地改变它。

第一个错误在这里:

Node root= head;
if(head==null){
    root.data=data;
    root.next=null;
    root.prev=null;
}

所以在这里你需要首先创建一个 Node 类的对象并将其分配给 root,这样代码就会看起来像:

Node root= head;
if(head==null){
    root=new Node();
    root.data=data;
    root.next=null;
    root.prev=null;
}

我遇到的另一个错误是if(head.data<data && head.next.data>data && head.next!=null).在这里,您应该先验证head.next,然后再在head.next.data中访问它。假设如果head.nextnull那么循环condition的评估是这样的。

1(head.data<data假设这个返回true,所以我们将检查下一个条件。

2(head.next.data>data现在如果head.next null那么这里的条件将是null.data,这将抛出NullPointerException。因此,在这里您还应该检查head.next是否为空。您正在这样做是下一个条件,但它在验证之前被执行。

所以在这里你只需要改变if语句的条件顺序,比如:if(head.data<data && head.next!=null && head.next.data>data)

这将解决您的问题。

 Node root= head;
if(head==null){
    root.data=data;

在这里,您正在尝试为空对象设置数据您应该首先为根分配内存例如

head = new Node();
root = head
//then continue your code

相关内容

最新更新