Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从上到下显示每个堆栈的内容?_Java_Stack - Fatal编程技术网

Java 如何从上到下显示每个堆栈的内容?

Java 如何从上到下显示每个堆栈的内容?,java,stack,Java,Stack,我想在执行下面的代码后输出每个堆栈的内容。到目前为止,它的输出为 Stack@568db2f2 Stack@378bf509 Stack@378bf509 但是我想要每个堆栈的内容 代码: publicstaticvoidmain(字符串[]args){ 堆栈a=新堆栈(); 堆栈b=新堆栈(); 堆栈c=新堆栈(); a、 推(28); b、 推(a.pop()); b、 peek(); c、 推(21); a、 推(14); a、 peek(); b、 推(c.pop()); c、 推(7

我想在执行下面的代码后输出每个堆栈的内容。到目前为止,它的输出为

Stack@568db2f2
Stack@378bf509
Stack@378bf509
但是我想要每个堆栈的内容

代码:

publicstaticvoidmain(字符串[]args){
堆栈a=新堆栈();
堆栈b=新堆栈();
堆栈c=新堆栈();
a、 推(28);
b、 推(a.pop());
b、 peek();
c、 推(21);
a、 推(14);
a、 peek();
b、 推(c.pop());
c、 推(7);
b、 推(a.pop());
b、 推(c.pop());
系统输出打印项次(a);
系统输出打印ln(b);
系统输出打印ln(b);
}
是的子类,您可以在其上使用和:

Stack Stack=新堆栈();
堆栈。推送(“!”);
堆栈推送(“世界”);
堆栈。推送(“”);
stack.push(“你好”);
对于(int i=stack.size()-1;i>=0;--i){
系统输出打印(一);
}
System.out.println();
然而,正如Federico指出的那样,如果在打印堆栈时不关心清空堆栈,那么您也可以调用
.pop()
循环它们,直到它们为空

但是,正如所指出的,您应该使用堆栈而不是
堆栈。实现
Deque
,并且可以轻松地迭代以打印其元素(从上到下):

Deque stack=newlinkedlist();
堆栈。推送(“!”);
堆栈推送(“世界”);
堆栈。推送(“”);
stack.push(“你好”);
for(字符串项:堆栈){
系统输出打印(项目);
}
System.out.println();

堆栈的默认
toString()
似乎打印堆栈在内存中的位置或类似的内容,而不是打印堆栈的内容。应为每个堆栈使用以下代码(stk是要打印其内容的原始堆栈taht):

//创建另一个临时堆栈
堆栈温度=新堆栈();
//分别打印原始堆栈(stk)的每个内容。
//将每个内容移动到临时堆栈(temp)以保留它。
而(!stk.empty())
{
System.out.println(stk.peek());
温度推动(stk.pop());
}
//将所有内容移回原始堆栈(stk)
而(!temp.empty())
{
stk.push(temp.pop());
}

如果您不需要在程序结束时仍然填充堆栈,您可以一次弹出一个元素(直到堆栈为空)并打印它。您希望每个堆栈内容的输出类型是什么<代码>字符串
[28,21,14,7]?@aKilleR它们最终都是空的吗?@EGS99,如果您使用
peek()
签出,它们将不会是空的
public static void main(String[] args) {
    Stack<Integer> a = new Stack<>();
    Stack<Integer> b = new Stack<>();
    Stack<Integer> c = new Stack<>();

    a.push(28);
    b.push(a.pop());
    b.peek();
    c.push(21);
    a.push(14);
    a.peek();
    b.push(c.pop());
    c.push(7);
    b.push(a.pop());
    b.push(c.pop());

    System.out.println(a);
    System.out.println(b);
    System.out.println(b);

}
//Create another temporary Stack
Stack<Integer> temp = new Stack<>();

//Print each content of the original Stack (stk) separately.
//Move each content to the temporary Stack (temp), in order to preserve it.
while(! stk.empty())
   {
       System.out.println(stk.peek());
       temp.push(stk.pop());
   }

//Move all the content back to the original Stack (stk)
while(! temp.empty())
   {
       stk.push(temp.pop());
   }