139 views
1 1 vote

Consider the following Python code fragment:

stack = []

while len(q) > 0:
    stack.append(q.pop(0))

while len(stack) > 0:
    q.append(stack.pop())

Here, $\texttt{q.pop(0)}$ removes the front element of the queue, and $\texttt{q.append(x)}$ inserts $\texttt{x}$ at the rear of the queue.

What does this code fragment do to the queue $\texttt{q}$?

  1. It leaves the queue unchanged.
  2. It reverses the items in the queue.
  3. It removes all items from the queue permanently.
  4. It sorts the queue in increasing order.

2 Answers

1 1 vote

The first loop removes items from the front of the queue and pushes them onto the stack.

Suppose the queue initially is:

$\texttt{q = ["A", "B", "C"]}$

After the first loop:

$\texttt{stack = ["A", "B", "C"]}$
$\texttt{q = []}$

Now the second loop pops from the stack. Since stack follows LIFO order, the popped order is:

$\texttt{C, B, A}$

These are appended back to the queue.

So the final queue becomes:

$\texttt{q = ["C", "B", "A"]}$

Therefore, the queue is reversed.

Correct Option: B

Answer:
Position:
Show:

Related questions

1 1 vote
2 2 answers
130
130 views
GO Classes asked Jul 9
130 views
Consider the following stack-based Python code:stack = [] n = 50 while n 0: stack.append(n % 2) n = n // 2 while len(stack) 0: print(stack.pop(), end="")What is printed...
5 5 votes
2 2 answers
253
253 views
GO Classes asked Jul 9
253 views
A stack is used to check whether parentheses, braces, and brackets are properly balanced.Consider the following two inputs:Input $1: \texttt{[()]\{\}\{[()()]()\}}$Input $...
6 6 votes
3 3 answers
338
338 views
GO Classes asked Jul 8
338 views
Suppose an intermixed sequence of stack push and pop operations is performed. The push operations push the integers $0$ through $9$ in order. The pop operations print the...
7 7 votes
3 3 answers
296
296 views
GO Classes asked Jul 8
296 views
A stack client reads tokens from left to right. If the token is a word, it is pushed onto the stack. If the token is $\texttt{-}$, one item is popped and printed.Consider...