这是用于堆栈的链表实现的弹出方法。如何在没有获得NPE的情况下在堆栈上弹出节点
当“弹出数量”等于“链接列表的大小”时,此方法将抛出NPE。
例子:
LinkedList list = new LinkedList();
list.push("A");
list.push("B");
list.push("C");
System.out.println(list.pop().getElement());
System.out.println(list.pop().getElement());
// the below code list.pop will have a null value.
System.out.println(list.pop().getElement());
System.out.println(list.pop().getElement());
public boolean isEmpty()
{
return head == null;
}
public Node pop()
{
if(!isEmpty())
{
head = head.getNext();
size--;
}
else if(isEmpty())
{
System.out.println("empty stack");
}
return head;
}
我的解决办法是重新编写这样的,但现在有被复制的返回头,我也没办法解决的代码。任何关于这个问题的指导都会有所帮助
public Node pop()
{
if(head != null)
{
return head;
}
if(!isEmpty())
{
head = head.getNext();
size--;
}
else if(isEmpty())
{
System.out.println("empty stack");
}
return head;
}
另一个问题:不知道,我应该叫可变头(链接列表的概念)或顶部(堆栈的概念)?请回答这个问题。
对于那些可能想知道为什么我返回一个节点对象的问题,我将会在稍后删除一个节点对象:我的教科书上说弹出意味着我需要返回弹出的节点以及将它从链接列表中移除,而不仅仅是删除它。
为什么你要从头开始做堆栈逻辑,为什么不用java一个 –
我必须实现自己的功能才能更深入地学习数据结构。 – Nicholas