2014-05-15 152 views
0

我想從單個鏈接列表中刪除末尾。我沒有一個尾部變量,它保持引用列表中的最後一項。因此,這是我的實現。我的問題是while循環如果我設置current=null;它不起作用(它不會刪除最後一個節點)。我必須設置current.next=null;
但是,我必須添加下一個current.next=null;。即使我說current = null;這並不意味着節點電流指向null.Can某人請解釋爲什麼我必須在那裏使用?從尾部刪除的鏈接列表

public void removeFromTail() throws EmptyStackException{ 
     if(head==null){ 
      throw new EmptyStackException("can't delete .Empty list");} 
     else if(head.next==null){ 
      head=null; 
     } 
     else{ 
      ListNode current=head; 
      while(current.next.next!=null){ 
       current=current.next; 
      } 


     current.next=null;} 
} 

回答

1

current是對鏈接列表中當前位置的引用。在while循環之後,current引用倒數第二項。當您說current.next = null時,您將當前對象的next變爲null。這使當前對象成爲最後一個對象。

當你說current = null,你只是設置你的本地參考變量爲null。換句話說,它不再提及你的名單。它指的是null

0

爲什麼不使用List接口的remove方法?

LinkedList<String> sss = new LinkedList<String>(); 
sss.add("a"); 
sss.add("b"); 
sss.remove(sss.size() - 1); // removes "b" 
+0

我只是爲了練習而自己寫這篇文章 –

+0

@Nik - BTW,LinkedList有'removeLast'方法... – MByD

1

當你做current=null;你設置的(本地)變量currentnull,但還是同一個對象指向你的列表,你想在它指向的最後一個對象,他next成員列表中的對象(someobject.next)停止指向那裏,所以你需要改變someobject.next的值,例如someobject.next = null;