Implement Queue using Stacks - aloalgo

Implement Queue using Stacks

Medium

You are tasked with implementing a queue data structure using two stacks. Your implementation should support all the essential operations of a queue: add, poll, peek.

  • add(x): Adds element x to the back of the queue. This operation does not return a value.
  • poll(): Removes and returns the element from the front of the queue.
  • peek(): Returns the element at the front of the queue without removing it.

Example 1

Input
q = QueueUsingStacks()
q.add(1)
q.peek()
q.poll()
Output
[1, 1]
Explanation:

Initial queue is empty. add(1) adds 1. The queue is [1]. peek() returns 1 without removing it. poll() removes and returns 1. The queue is now empty.

Example 2

Input
q = QueueUsingStacks()
q.add(1)
q.add(2)
q.poll()
q.add(3)
q.poll()
q.poll()
Output
[1, 2, 3]
Explanation:

Initial queue is empty. add(1), add(2), and add(3) add elements to the queue. The queue is [1, 2, 3]. The first poll() removes and returns 1. The second poll() removes and returns 2. The third poll() removes and returns 3. The queue is now empty.

Example 3

Input
q = QueueUsingStacks()
q.add(1)
q.add(2)
q.poll()
q.add(3)
q.poll()
q.poll()
Output
[1, 2, 3]
Explanation:

Initial queue is empty. add(1) and add(2) add elements to the queue. The queue is [1, 2]. The first poll() removes and returns 1. add(3) adds 3 to the back. The queue is now [2, 3]. The second poll() removes and returns 2. The third poll() removes and returns 3. The queue is now empty.

Loading...
Input
q = QueueUsingStacks()
q.add(1)
q.peek()
q.poll()
Output
[1, 1]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!