Consider the following statements : S1 : A queue can be implemented using two…
2016
Consider the following statements :
S1 : A queue can be implemented using two stacks.
S2 : A stack can be implemented using two queues.
Which of the following is correct ?
- A.
S1 is correct and S2 is not correct.
- B.
S1 is not correct and S2 is correct.
- C.
Both S1 and S2 are correct.
- D.
Both S1 and S2 are not correct.
Attempted by 990 students.
Show answer & explanation
Correct answer: C
Answer: Both statements are correct.
Implementing a queue using two stacks (amortized O(1) per operation):
Maintain two stacks: stack_in and stack_out.
Enqueue(x): push x onto stack_in.
Dequeue(): if stack_out is empty, pop all elements from stack_in and push them onto stack_out; then pop from stack_out.
Complexity: Amortized O(1) per enqueue/dequeue because each element is moved at most once between stacks.
Implementing a stack using two queues (example: push-costly method):
Maintain two queues: q1 (holds current stack order) and q2 (temporary).
Push(x): enqueue x into q2, then dequeue all elements from q1 and enqueue them into q2; swap q1 and q2. Now q1 has the new element at the front (top of stack).
Pop(): dequeue from q1 (this returns the last pushed element).
Complexity: Push is O(n) and pop is O(1) in this method. There is an alternative (pop-costly) method where push is O(1) and pop is O(n).