Implement Queue using Two Stacks – Java Code & Algorithm

How to implement a queue using two stacks. In this tutorial, I am going to discuss how to implement a first in first out (FIFO) queue using only two stacks.

In this problem, we are going to implement following methods of QueueUsingStack class:

void push(int x) – Insert an element x.
int pop() –  Removes the element (In FIFO order).
int peek() – Returns the element which is present at the front of the queue.
boolean empty() – Returns true if no element is present else false.

For example –

Before solving this problem let’s first understand the difference between queue and stack data structure.

Queue

Queue is a First-In, First-Out (FIFO) data structure. The element which we enqueued first is the first element to be dequeued.

In queue, inserting an element is called as enqueue and deleting an element is called as dequeue. Insertion happens at one end called rear and deletion happens at other end called front.

Programming questions on queue

Stack

Stack is a Last-In, First-Out (LIFO) data structure. The element which we pushed at last is the first element to be popped out.

Inserting an element in a stack is called as push and deleting an element is called as pop.

Programming questions on stack

Programming video tutorials on stack

Java program to check for balanced parentheses using stack

queue using two stacks

Implement Queue using Two Stacks – Java Code

Let’s discuss how we can impelement a queue using two stacks and write it’s java code.

The idea here is to push the element in a first stack. When the pop operation is called pop the element from second stack. If second stack is empty and first stack is not empty then pop all the elements from first stack and push them in a second stack.

It ensures that whenever we pop from the second stack, we get the element which is inserted first (FIFO order).

Tagged , , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.