这是一本测试你关于 LinkedLists、Stacks 和 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 );
LL:a = {2, 3, 5, 7}
for ( int i : a )
{
System.out.print( i + " " );
s.push( i );
q.add( i );
}
打印输出:2 3 5 7
堆栈:s = {2, 3, 5, 7}
队列:q = {2, 3, 5, 7}
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}
队列: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
2 3 5 7 12 10 8 7
但是,这个问题的答案是这样的:
2 3 5 7
7 5 3 2
2 3 5 7 7 8 10 12
如您所见,队列打印中的结果不匹配。我重新解决了该问题两次,但无法确定我在添加 (s.pop() + 5
) 或 .pop()
打印中是否做错了。有人可以告诉我我做错了什么吗?
最佳答案
我认为你的错误就在这里,在第三个代码片段中:
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, 3, 5, 7, 7, 8, 10, 12]
我认为其他一切都很好。
关于java - 堆栈、队列和链表脑筋急转弯的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24192191/