stack and queue
I am doing revision for my exams and I came across this question which I need to find the contents of Q1 after the following code are executed.
The datas
5, 7, 12, 4, 0, 4, 6, 8, 67, 34, 23, 5, 0, 44, 33, 22, 6, 0
The pusedo-code
Q1=createQueue
S1=createStack
loop (not end of file)
read number
if (number not 0)
pushStack (S1,number)
else
popStack (S1,x)
popStack (S1,x)
loop (not empty S1)
popStack (S1,x)
enqueue (Q1,x)
end loop
end if
end loop
Here is my solutions
if number is not 0, push the numbers to the stack so now the stack becomes
6
22
33
44
5
23
34
67
8
6
4
4
12
7
5
else pop the first 2 elements of the stack so now the stack becomes
33
44
5
23
34
67
8
6
4
4
12
7
5
3.loop stack !empty, pop the stack and enqueue in Q1.so now the stack is empty and the queue becomes
5,7,12,4,4,6,8,67,34,23,5,44,33
33 is the first in the queue and 5 is the last of the queue.
I double checked with the answer provided and found out that my answers is different
The provided answer
7,5,34,67,8,6,4,33,44
I am not sure who is correct. please help.
You reasoning is in the correct direction, but there are three zeros in the input and you only seem to do the else
logic for the last one. Keep in mind that the else clause is within the loop too. Try processing the input until each of them one by one.
上一篇: c ++实现组合队列/堆栈
下一篇: 堆栈和队列