2014-02-06 50 views
0

我試圖創建一個新的LinkedListNode對象,因爲我反過來解析了char[]。然後我想這些在for循環中創建並鏈接LinkedList

char[] totalnum = (total + "").toCharArray(); 
    for (int i = totalnum.length; i > 0; i--) { 
     LinkedListNode sum = new LinkedListNode(totalnum[i]); 
     sum.next = null; 
    } 

鏈接在這裏是我的LinkedListNode類:

public class LinkedListNode { 
    int data; 
    public LinkedListNode next; 

    // constructor 
    public LinkedListNode(int newData) { 
     this.next = null; 
     this.data = newData; 
    } 
} 

我想知道我怎麼能去這樣做。我是Java新手,所以這讓我很難過!我知道我應該在每次迭代中創建一個新的LinkedListNode對象,但這是我得到的

+0

對不起,我h​​tought我完成了! – Liondancer

回答

1
public class LinkedListNode { 
    int data; 
    private LinkedListNode next; 

    public LinkedListNode(int data) { 
     this.data = data; 
    } 

    public void setNext(LinkedListNode next) { 
     this.next = next; 
    } 

    public LinkedListNode getNext() { 
     return next; 
    } 
} 

char[] totalNum = (total + "").toCharArray(); 
int length = totalNum.length; 

LinkedListNode tail /*or 'head', whatever suits you*/ = new LinkedListNode(totalNum[length - 1]); 
LinkedListNode newNode; 
LinkedListNode previousNode = tail; 

for (int i = length - 2; i >= 0; i--) { 
    newNode = new LinkedListNode(totalNum[i]); 
    previousNode.setNext(newNode); 
    previousNode = newNode; 
} 
+0

變了謝謝! – Liondancer

+0

@Liondancer更新回答 – aasu

+0

我的char數組是'7550'。然而,當我嘗試你的代碼時,我得到輸出48,48,53,53作爲我的鏈表,當我返回尾 – Liondancer