用java在已排序的链表中创建和插入数字
我试图在循环排序的链表中创建和插入数字,但我得到一个错误 第45行出现空指针异常。 任何人都能看出我做错了什么用java在已排序的链表中创建和插入数字,java,Java,我试图在循环排序的链表中创建和插入数字,但我得到一个错误 第45行出现空指针异常。 任何人都能看出我做错了什么 public class nodes { private int data; private nodes next; public nodes(int data){ this.data = data; } //standard getters and setters. See below if you really want
public class nodes {
private int data;
private nodes next;
public nodes(int data){
this.data = data;
}
//standard getters and setters. See below if you really want to
public static void main (String args[]) throws IOException{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter 0 to stop");
nodes headnode =null;
int n =Integer.parseInt(br.readLine());
while(n!=0){
nodes insert = null;
System.out.println("enter the value");
int t =Integer.parseInt(br.readLine());
insert.setdata(t);
nodetoinsert(insert, headnode);
}
}
private static void nodetoinsert(nodes p, nodes headnode){
nodes previousnode =null;
if (headnode ==null){
headnode.setdata(p.getdata());
}else if(headnode.getdata()>(p.getdata())){
p.setNext(headnode);
}else{
nodes currentnode= headnode.getnext();
if(currentnode.getnext() == null)
currentnode.setNext(headnode);
while(currentnode.getdata()<= p.getdata()&& currentnode !=headnode){
previousnode =currentnode;
currentnode =currentnode.getnext();
}
previousnode.setNext(p);
p.setNext(currentnode);
}
}
public void setdata(int data){
this.data=data;
}
public int getdata(){
return data;
}
public void setNext(nodes next){
this.next=next;
}
public nodes getnext(){
return this.next;
}
}
在headnode上调用setdata方法,该方法为null=>NPE。与插入节点相同。有两个问题:
1) 节点headnode=null代码>
仍然作为null传递给nodetoinsert(insert,headnode)代码>
初始化头节点<代码>节点头节点=新节点(0)代码>
2) 您正在尝试对空引用调用方法。请参阅下文:
while(n!=0){
**nodes insert = null;**
System.out.println("enter the value");
int t =Integer.parseInt(br.readLine());
**insert**.setdata(t);
nodetoinsert(insert, headnode);
}
节点引用变量未初始化。您需要初始化该节点引用。如下所示:
while(n!=0){
nodes insert = new nodes(0);
System.out.println("enter the value");
int t =Integer.parseInt(br.readLine());
insert.setdata(t);
nodetoinsert(insert, headnode);
}
如果需要进一步帮助,请告诉我。请在第45行标记。我想你的问题是:nodesinsert=null代码>然后插入.setdata(t)代码>,这可能引发异常。但是你也可以发布一致的stacktrace,这是java。我建议您编写以大写字母开头的类名,如节点
。method(“对象的函数”)通常是用case编写的。您的nodetoinsert
将成为nodetoinsert
。它更具可读性,像Eclipse这样的IDE可以更好地处理它。想知道更多吗?以下是指引:
while(n!=0){
nodes insert = new nodes(0);
System.out.println("enter the value");
int t =Integer.parseInt(br.readLine());
insert.setdata(t);
nodetoinsert(insert, headnode);
}