2017-02-22 68 views
0

我想添加一個節點到列表的末尾,這就是我想出的。我只是想知道如果我設置尾巴=頭,如果這是尾巴=添加同樣的事情?或者如果我有tail = head.next,如果它與tail = add相同? 在此先感謝Java節點清晰度

public BasicLinkedList<T> addToEnd(T data) { 
    Node add= new Node(data); 
    Node curr=head; 
    if(size==0){ 
     head= add; 
     tail=head; //is it okay to make this= head? Or should it be =add? 
    }else if(size==1){ 
     head.next=add; 
     tail=head.next; //is it okay to make this= head.next? Or should it be =add? 
    }else{ 
     while(head.next!= null){ 
      curr=head.next; 
     }curr.next = add; 
     tail = add; 
    } 
    size++; 
    return this; 

} 
+0

我相信你可能有一個邏輯問題。 'while(head.next!= null){',那應該檢查'curr.next',否則你會發現自己處於一個無限循環中,因爲頭部在循環中沒有改變,所以它總是會是真的。 –

+0

提示:你不需要'if(size == 1)'塊。 – progyammer

回答

2

爲了回答

//is it okay to make this= head? Or should it be =add? 

是無論是罰款,headadd的是同一個對象的引用。

//is it okay to make this= head.next? Or should it be =add? 

再次,無論是在這裏很好,也就像head.nextadd是同一個對象的引用。

+0

這是正確的答案。 – VHS