我想從單個鏈接列表中刪除末尾。我沒有一個尾部變量,它保持引用列表中的最後一項。因此,這是我的實現。我的問題是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;}
}
我只是爲了練習而自己寫這篇文章 –
@Nik - BTW,LinkedList有'removeLast'方法... – MByD