• edited by
31,666 views
40 40 votes

What is the minimum number of stacks of size $n$ required to implement a queue of size $n$?

  1. One
  2. Two
  3. Three
  4. Four

7 Answers

Best answer
48 48 votes

A queue can be implemented using two stacks.

Let queue be represented as " $q$ "
and stacks used to implement $q$ be "stack1" and "stack2".

$q$ can be implemented in two ways:

Method 1 (By making EnQueue operation costly)

This method makes sure that newly entered element is always at the bottom of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used.

$enQueue(q, x)$

  1. While stack1 is not empty, push everything from stack1 to stack2.
  2. Push $x$ to stack1 (assuming size of stacks is unlimited).
  3. Push everything back to stack1.

$dnQueue(q)$

  1. If stack1 is empty then error
  2. Pop an item from stack1 and return it


Method 2 (By making deQueue operation costly)

In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.
$enQueue(q,  x)$

  1. Push $x$ to stack1 (assuming size of stacks is unlimited).

$deQueue(q)$

  1. If both stacks are empty then error.
  2. If stack2 is empty
    While stack1 is not empty, push everything from stack1 to stack2.
  3. Pop the element from stack2 and return it.

Correct Answer: $B$

• edited by
1 1 vote
Two. One stack is used for enqueue operations, and the other stack is used for dequeue operations. The enqueue stack is used to push elements onto the queue, and the dequeue stack is used to pop elements off of the queue. To implement a queue using stacks, the elements are first pushed onto the enqueue stack. When a dequeue operation is performed, the elements are popped from the enqueue stack and pushed onto the dequeue stack. The top element of the dequeue stack is then returned as the dequeued element. This process ensures that the first element pushed onto the queue is also the first element to be popped off of the queue, which is the behavior of a queue.
Answer:
Position:
Show:

Related questions

53 53 votes
7 answers 7 answers
25.1k
25.1k views
Kathleen asked Oct 9, 2014
25,146 views
Consider the following statements:First-in-first out types of computations are efficiently supported by STACKS.Implementing LISTS on linked lists is more efficient than i...
41 41 votes
2 answers 2 answers
9.8k
9.8k views
Kathleen asked Sep 14, 2014
9,778 views
Consider any array representation of an $n$ element binary heap where the elements are stored from index $1$ to index $n$ of the array. For the element stored at index $i...
84 84 votes
9 answers 9 answers
41.3k
41.3k views
Kathleen asked Sep 14, 2014
41,333 views
Which of the following does not interrupt a running process?A deviceTimerScheduler processPower failure