[英]Delete last element in singleLinked List
我正在制作一個簡單的鏈表,並且試圖實現一種允許刪除鏈表的最后一個節點的方法。 在某些時候,我的方法是錯誤的,我不確定錯誤在哪里以及如何解決。 這是代碼!
public Nodo deleteEnd() {
Nodo aux;
if (head == null) {
throw new NoSuchElementException("Element cant be deleted");
} else {
aux = head;
while (aux.next.next != null) {
aux = aux.next;
}
size--;
}
return aux;
}
您需要將最后但並非最不重要的節點的next
分配為null
:
if(head.next == null) {
// head is last!
head = null;
size = 0;
} else {
previous = head;
current = head.next;
// while current is not last, keep going
while(current.next != null) {
previous = current;
current = current.next;
}
// current is now on last!
previous.next = null;
size--;
}
嘗試減少一個.next
:
while (aux.next != null) {
aux = aux.next;
}
public Nodo deleteEnd() {
if (head == null) {
throw new NoSuchElementException("Element can't be deleted");
}
Nodo current = head;
Nodo next = current.next;
// Check if there is only the head element.
if ( next == null )
{
size--;
head = null;
return current;
}
// Skip to the end.
while (next.next != null) {
current = next;
next = next.next;
}
// Break the link to the next element.
current.next = null;
size--;
return next;
}
加
aux.next = null;
在while循環之后-那么將沒有對最后一個元素的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.