[英]Linked list insert a node in sorted linked list
强调文本,我需要传递链接列表的标题和要插入到该链接列表中的数据。假设列表按排序顺序,我需要检查每个节点的数据并插入新节点以给出新排序的列表。
我正在获取空指针异常,我需要知道我在做什么错
/*
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;
}
我在while循环内的第二个if语句处获得空指针异常。
Node root= head;
if(head==null){
root.data=data;
在这里,您尝试为空对象设置数据,应首先为根分配内存,例如
head = new Node();
root = head
//then continue your code
我在您的代码中发现了一些错误,这些错误可能会导致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.next
为null
则循环condition
的评估如下。
1) head.data<data
因此假设此返回true
因此我们将检查下一个条件。
2) head.next.data>data
现在,如果head.next
为null
那么这里的条件将为null.data
,这将引发NullPointerException
。 因此,在这里您还应该检查head.next
不为null。 您正在执行下一个条件,但在验证之前将执行它。
所以在这里,您只需要更改if
语句的条件顺序即可: if(head.data<data && head.next!=null && head.next.data>data)
。
这样可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.