我正在制作一个简单的链表,并且正在尝试实现一种允许我删除链表的最后一个节点的方法。在某些时候,我的方法是错误的,我不确定错误在哪里以及如何修复它。这是代码!
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--;
}
关于java - 删除单链表中的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783507/