In: Computer Science
What is the output of the StackQueueMystery algorithm (below) when we have enqueued 1, 2, 5, 6, 3, 7, 4, 10, 8, 9 on q and pushed 8, 6, 9, 7, 10, 5, 4, 3, 2, 1 on stk (in that order) before calling this algorithm. Show your work.
StackQueueMystery:
Input: stk: stack with integers 1-n
Input: q: queue with integers 1-n
Input: n: size and range of stk and q
Pseudocode:
count = 0
while stk and q are not empty:
{
x = x0 = stk.pop()
y = y0 = q.dequeue()
while x != y0 and stk is not empty
x = stk.pop()
while y != x0 and q is not empty
y = q.dequeue()
count = count + 1
}
return count
Solution:-
The output of the StackQueueMystery algorithm will be 5 as the value of the count will be 5 at the end.
In this question we are given with a stack and a queue. The sequence of push and enqueue that is given can be shown as
as per the pseudo code, the value of count initially is 0 and changes as the while loop is executed
for 1st iteration
for 2nd iteration
For the 3rd iteration
while x! = y0 and stk is not empty // true .
it pops elements until its found 5 or stk becomes empty.
5 was found at 5th pos.
while y!=x= and q is not empty // true.
it continues until q becomes empty or its finds 3 .
3 was found at 5th pos.
for the 4th iteration
while x! = y0 and stk is not empty // true .
it pops elements until its found 7 or stk becomes empty.
7 was found at 7th pos.
while y!=x= and q is not empty // true.
it continues until q becomes empty or its finds 10 .
10 was found at 8th pos.
for the 5th iteration
while x! = y0 and stk is not empty // true .
it pops elements until its found 8 or stk becomes empty.
8 was found at 10th pos.
while y!=x= and q is not empty // true.
it continues until q becomes empty or its finds 9 .
9 was found at 10th pos.
here both the stk and q got empted and the value of count becomes 5.
if u like my answer then please
give a thumbs up..!!