Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Implement Queue Using Stacks

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

Here our objec­tive is to imple­ment queue using stacks.

Approach:

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

Exam­ple:

Implement-Queue-Using-Stacks

Implement-Queue-Using-Stacks

Com­plete Code:


Out­put:

POP from Queue 10

You may also like...