【发布时间】:2015-09-30 09:49:24
【问题描述】:
这是一个栈的链表实现的pop方法。
当“pops 数”等于“链表的大小”时,此方法将抛出 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;
}
另一个问题:不确定,我应该调用变量head(链表概念)还是top(堆栈概念)?请也回答这个问题。
对于那些可能想知道为什么我要返回稍后将被删除的节点对象的人,我的论点是:我的教科书说 pop 意味着我需要返回弹出的节点并将其从链表中删除,而不是仅仅删除它。
【问题讨论】:
-
为什么你要从头开始做堆栈逻辑,为什么不使用 java one
-
我必须自己实现才能更深入地学习数据结构。
标签: java data-structures linked-list stack