Java 堆栈、队列和LinkedList脑筋急转弯的输出

Java 堆栈、队列和LinkedList脑筋急转弯的输出,java,stack,queue,Java,Stack,Queue,这是一本在LinkedList、Stack和Queue上测试您的书中出现的问题。目标是从这段代码中打印出所需的输出。我已经将代码与我的分析结合起来了 LinkedList<Integer> a = new LinkedList<Integer>(); Stack<Integer> s = new Stack<Integer>(); Queue<Integer> q = new LinkedList<Integer>();

这是一本在LinkedList、Stack和Queue上测试您的书中出现的问题。目标是从这段代码中打印出所需的输出。我已经将代码与我的分析结合起来了

LinkedList<Integer> a = new LinkedList<Integer>();
Stack<Integer> s = new Stack<Integer>();
Queue<Integer> q = new LinkedList<Integer>();

a.add( 2 );
a.add( 3 );
a.add( 5 );
a.add( 7 );
打印输出:
2 3 5 7

堆栈:
s={2,3,5,7}

for ( int i : a )
{
    System.out.print( i + " " );
    s.push( i );
    q.add( i );
}
System.out.println();

for ( int i : a )
{
    s.push( i );
    q.add( s.pop() + 5 );
    System.out.print( s.pop() + " " );
}
队列:
q={2,3,5,7}

for ( int i : a )
{
    System.out.print( i + " " );
    s.push( i );
    q.add( i );
}
System.out.println();

for ( int i : a )
{
    s.push( i );
    q.add( s.pop() + 5 );
    System.out.print( s.pop() + " " );
}
堆栈:
s={2,3,5,7,2,3,5,7}

for ( int i : a )
{
    System.out.print( i + " " );
    s.push( i );
    q.add( i );
}
System.out.println();

for ( int i : a )
{
    s.push( i );
    q.add( s.pop() + 5 );
    System.out.print( s.pop() + " " );
}
队列:
q={2,3,5,7,12,10,8,7}
。这是由于
s.pop()+5

打印输出:
7 5 3 2

System.out.println();

for ( int i : a )
{
    System.out.print( q.remove() + " " );
    System.out.print( q.remove() + " " );
}
打印输出:
2 3 5 7 12 10 8 7

总之,我的打印输出是:

2 3 5 7

7 5 3 2

System.out.println();

for ( int i : a )
{
    System.out.print( q.remove() + " " );
    System.out.print( q.remove() + " " );
}
2357121087

然而,这个问题的答案是:

2 3 5 7

7 5 3 2

System.out.println();

for ( int i : a )
{
    System.out.print( q.remove() + " " );
    System.out.print( q.remove() + " " );
}
23578102

如您所见,打印队列中的结果不匹配。我重复了两次该问题,但无法确定是在添加(
s.pop()+5
)还是在打印时出错。有人能告诉我我做错了什么吗?

我想你的错误在这里,在第三段代码中:

for ( int i : a )
{
    s.push( i );
    q.add( s.pop() + 5 );
    System.out.print( s.pop() + " " );
}
i
被推到堆栈上后,它立即被
q.add(s.pop()+5)弹出。执行过程如下:

之前:

s == [2, 3, 5, 7]
q == [2, 3, 5, 7]
第一次迭代:

2 is pushed onto s
2 is popped off of s
5 is added to 2
7 is added to q
7 is popped off s and printed
3 is pushed onto s
3 is popped off of s
5 is added to 3
8 is added to q
5 is popped off s and printed
第二次迭代:

2 is pushed onto s
2 is popped off of s
5 is added to 2
7 is added to q
7 is popped off s and printed
3 is pushed onto s
3 is popped off of s
5 is added to 3
8 is added to q
5 is popped off s and printed
等等等等

因此,循环之后的正确结果应该是空堆栈和队列,即:

[2, 3, 5, 7, 7, 8, 10, 12]

我想其他一切都好。

啊。。对就这样。非常感谢。@青菜没问题!只是一个提示--您可以随时将代码键入IDE,并使用调试器查看此类事件的具体情况。实际上,您可以稍微深入地解释一下在
q.add(s.pop()+5)
上发生的事情吗?哪个先执行,是
q.add
还是
s.pop()
还是
s.pop()+5
?@绿卷心菜刚刚更新了我的答案。操作/方法的参数总是在执行该操作/方法之前进行求值。因此,在调用
q.add()
之前,必须先计算
s.pop()+5
。在计算
+
之前,必须先计算
s.pop()
5
。@纸上最好的方法是假装你是一台计算机!只要一行一行地做代码告诉你要做的事情,分解事情,跟踪方法调用,等等。不幸的是,我不能说得比这更具体(这是我做这类事情时通常要考虑的),但只要你清除了关于代码应该做什么的任何先入之见,你通常会做得很好。