我想創建並在循環排序的鏈接列表中插入數字,但我得到一個錯誤,因爲 行號中的空指針異常。 45. plzz任何人都可以看到我在這裏做錯了什麼。創建並在java中的排序鏈接列表中插入數字
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;
}
}
請標記第45行。我想你的問題是這裏:'nodes insert = null;'然後'insert.setdata(t);',這可能會拋出異常。但你也可以發佈一致的堆棧跟蹤。 – pzaenger 2014-09-19 08:51:08
這是java。我建議你寫一個以大寫字母開頭的類名,比如'Nodes'。 Methos(「對象的功能」)通常寫成camelCase。你的'nodetoinsert'會變成'nodeToInsert'。它更易讀,像Eclipse這樣的IDE可以更好地處理它。想知道更多嗎?這裏是指導方針:http://www.oracle.com/technetwork/java/codeconventions-135099.html – Atmocreations 2014-09-19 08:59:41