2011-09-29 67 views
-1

我們正在學習使用節點的鏈接列表,我不確定我是否正確執行此操作。我們假設只做一個簡單的列表,但是當我去運行程序時,我得到指向showList()方法的nullpointerException,但是當我嘗試不使用該方法時,則根本沒有打印出任何東西。請任何幫助,非常感謝。使用節點的列表

public class node { 
     public int dataitems; 
     public node next; 
     node front; 

public void initList(){ 
    front = null; 
} 

public node makeNode(int number){ 
    node newNode; 
    newNode = new node(); 
    newNode.dataitems = number; 
    newNode.next = null; 
    return newNode; 
} 

public boolean isListEmpty(node front){ 
    boolean balance; 
    if (front == null){ 
     balance = true; 
    } 
    else { 
     balance = false; 
    } 
    return balance; 

} 

public node findTail(node front) { 
    node current; 
    current = front; 
    while(current.next != null){ 
     //System.out.print(current.dataitems); 
     current = current.next; 

    } //System.out.println(current.dataitems); 
    return current; 
} 

public void addNode(node front ,int number){ 
    node tail; 
    if(isListEmpty(front)){ 
     front = makeNode(number); 
    } 
    else { 
     tail = findTail(front); 
     tail.next = makeNode(number); 
    } 
} 

public void printNodes(int len){ 

    int j; 
    for (j = 0; j < len; j++){ 
     addNode(front, j); 
    } showList(front); 
} 

public void showList(node front){ 
    node current; 
    current = front; 
    while (current.next != null){ 
     System.out.print(current.dataitems); 
     current = current.next; 
    } 
    System.out.println(current.dataitems); 
} 


public static void main(String[] args) { 
    node x = new node(); 

    x.printNodes(50); 
    } 

     } 

回答

1

問題與addNode方法的變量範圍有關。

public void addNode(node front ,int number){ 
    node tail; 
    if(isListEmpty(front)){ 
     front = makeNode(number); //reassigns the node front parameter 
    } 
    else { 
     tail = findTail(front); 
     tail.next = makeNode(number); 
    } 
} 

你的「前部」的分配僅分配makeNode(數)值到本地變量。您需要使用this.front將makeNode(number)分配給節點類的實例變量或重構變量名稱。

public void addNode(node front ,int number){ 
    node tail; 
    if(isListEmpty(front)){ 
     //assigns a value to the member variable "front" of your node instance 
     this.front = makeNode(number); 
    } 
    else { 
     tail = findTail(front); 
     tail.next = makeNode(number); 
    } 
} 
+0

謝謝這工作完美 – TMan

1

你這樣做

node current; 
current = front; 

但你永遠不初始front,所以當你打電話current.nextcurrent爲空。所以你不能獲得下一個...

順便說一句,爲什麼不清理的代碼,做

node current = front; 

此外,在Java類的名稱應該大寫,所以node應該Node