我们如何将一个堆栈完全弹出到另一个堆栈中

发布于 2025-02-01 01:41:27 字数 256 浏览 1 评论 0原文

我有这个代码:

for (int i = 0; i < StackA.capacity(); i++) {
    StackB.push(StackA.get(i));
}

但是这给了我这个错误:

Array index out of range: 0
    at java.base/java.util.Vector.get

有人可以帮助我确定自己的错误吗?

I have this code:

for (int i = 0; i < StackA.capacity(); i++) {
    StackB.push(StackA.get(i));
}

but it's giving me this error:

Array index out of range: 0
    at java.base/java.util.Vector.get

Can anybody help me identify my mistake?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

近箐 2025-02-08 01:41:27

如果您正在寻找的是如何将元素添加到stackb而无需删除atacka的元素,那么您可以使用Iterator来traverse 代码> stacka ,然后将其元素添加到stackb中。

//Adding elements within stackB without consuming stackA
for (Iterator<Integer> it = stackA.iterator(); it.hasNext(); ) {
    stackB.push(it.next());
}

否则,正如注释中建议的那样,如果在stacka中消耗元素不是问题,那么您可以简单地迭代第一个堆栈,直到它为空并将每个元素弹出到stackb 在每次迭代期间。

//Adding elements within stackB by consuming stackA
while (!stackA.empty()) {
    stackB.push(stackA.pop());
}

If what you're looking is how to add elements into stackB without removing the elements from atackA, then you could use an Iterator to traverse stackA and add its elements into stackB.

//Adding elements within stackB without consuming stackA
for (Iterator<Integer> it = stackA.iterator(); it.hasNext(); ) {
    stackB.push(it.next());
}

Otherwise, as it has been suggested in the comments, if consuming the elements within stackA is not a problem, you could simply iterate your first stack until it's empty and popping each element into stackB during every iteration.

//Adding elements within stackB by consuming stackA
while (!stackA.empty()) {
    stackB.push(stackA.pop());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文