gpt4 book ai didi

java - 在堆栈中实现 pop() 方法

转载 作者:行者123 更新时间:2023-11-30 06:10:20 25 4
gpt4 key购买 nike

我在 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() 方法的方式是否正确?

最佳答案

您的 top=top.next; 将不会被执行,因为之前行中的返回语句。您必须保存临时弹出的对象以设置新的顶部。

关于java - 在堆栈中实现 pop() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35924022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com