Be the first user to complete this post

  • 0
Add to List
Medium

108. Queue with Stacks: Efficient Implementation Using Stack Operations

Objective: We know that Queue is FIFO (First-in-First-Out) and Stack is LIFO ( Last-in-First-Out).

Here our objective is to implement a queue using stacks.

Approach:

  • Take 2 Stacks, stack1 and stack2.
  • stack1 will be used as the back of the Queue and stack2 will be used as the front of the Queue.
  • Push() operations will be done on stack1, and peek() and pop() operations will be done on stack2.
  • When peek() and pop() are called, check if stack2 is empty, if yes then move all the elements from stack1 and push them into stack2.

Example:

Implement Queue Using Stacks
 

Output:

POP from Queue 10