我有一个 Java 中的 pop()
方法,我想实现它。这是我的代码:
public E pop() {
if (top == null) {
throw new NoSuchElementException();
} else {
return top.element;
top = top.next;
}
}
但我的书是这样做的:
public E pop() {
if (top == null) {
throw new NoSuchElementException();
}
E tmp = top.element;
top = top.next;
return tmp;
}
我执行 peek() 方法的方式正确吗?
最佳答案
由于前一行中的 return 语句,您的 top=top.next;
将不会被执行。您必须保存临时弹出的对象才能设置新顶部。
关于java - pop()方法在栈中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35924022/