2013-03-01 75 views
1

嘿傢伙我試圖實現單鏈表的appeed方法時遇到了問題。 這裏是代碼:單鏈表添加方法

public void append (int item) { 
//inserts item to the end of the list 
     if (head == null){ 
      head = new LinkInt(); 
      curr = head; 
      curr.elem = item; 
     } 
     else{ 
     LinkInt temp = head; 
     while (temp.next != null){ 
     temp = temp.next;} 
     temp.elem = item; 
     } 


} 

,這裏是我的打印方法(不知道其正確的爲好):

public void print() { 
//outprint the array 
    //ie. <1, 2, |3, 4> 
    if ( head == null) { 
     System.out.print("<"); 
     System.out.print(">"); 
    } 
    else{ 
    LinkInt temp = head; 
    System.out.print("<"); 
    while (temp != null) { 
     if (temp == curr){ 
       System.out.print("|" + temp.elem + ","); } 
     else{ 
     System.out.print(temp.elem); 
     System.out.print(",");} 
     temp = temp.next; 
    } 
    System.out.print(">"); 
    } 
} 

}

繼承人的問題:

讓利說上面3 - >>>我得到< | 3> ,但如果我做了後 - 5 >>>>我得到< | 5>刪除我的第一個項目。

幫我個忙,請:(

+1

爲什麼不儲存參考尾部元素。會讓事情變得更快。 – 2013-03-01 05:27:31

回答

0
LinkInt temp = head; 
while (temp.next != null){ 
    temp = temp.next; 
} 
temp.elem = item; 

這樣做是什麼 - temp.next is null3已經插入。因此,它會轉到temp.elem = item並覆蓋您的現有值。做這樣的事情: -

LinkInt temp = head; 
while (temp.next != null){ 
    temp = temp.next; 
} 
//temp.elem = item; -Not needed. 

temp1= new LinkInt(); 
temp1.elem = item; 
temp1.next = null; 
temp.next = temp1; 
+0

哇,非常感謝它! – Envix 2013-03-01 04:47:04

+0

爲什麼downvote,這個答案似乎對我?任何解釋爲什麼它是錯誤的,以便我也可以清除我的疑惑:-) – 2013-03-01 04:47:33

+1

我打算點擊檢查,但我偶然點擊downvote :(對不起,另外1個問題我如何修改我的打印(),以便在最後一個沒有逗號的元素?:D – Envix 2013-03-01 04:55:08

1

這些語句後:

while (temp.next != null) 
{ 
    temp = temp.next; 
} 

做這樣的:

tmp1= new LinkInt(); 
tmp1.elem = item; 
tmp1.next = null 

tmp.next = tmp1 

,而不是這樣的:

temp.elem = item; 

嘗試一下本作打印方法:

public void print() 
{ 
    //outprint the array 
    //ie. <1, 2, |3, 4> 
    if ( head == null) 
    { 
     System.out.print("<"); 
     System.out.print(">"); 
    } 
    else 
    { 
     LinkInt temp = head; 
     System.out.print("<"); 
     while (temp->next != null) 
     { 
      System.out.print("|" + temp.elem + ","); 
      temp = temp.next; 
     } 
     System.out.print("|" + temp.elem);} 
     System.out.print(">"); 
    } 

} 
+0

感謝它的作品:) – Envix 2013-03-01 04:47:29

+0

沒問題...我們歡迎您! :) – codeMan 2013-03-01 04:54:59

+0

1個問題我如何修改我的print(),以便在沒有逗號的最後一個元素之後? :D – Envix 2013-03-01 05:00:47

0

有法這樣

public void append(int item) 
{ 
    LinkInt l = new LinkInt(); 
    l.elem = item; 
    if (head == null) 
     head = l; 
    else { 
     LinkInt tmp = head; 
     while (tmp.next != null) 
      tmp = tmp.next; 
     tmp.next = l; 
} 
+0

您不會向節點的下一個部分添加任何內容到新創建的節點,我想你假設'新的LinkInt()'實際上給節點賦一個'null'值給它的'next'部分。 – 2013-03-01 04:49:10