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 –
1 2 3 4 5 6 |
QueueUsingStack qu = new QueueUsingStack(); qu.push(5); // Element in queue is : [5] qu.push(4); // elements are : [5, 4] qu.peek(); // return 5 qu.pop(); // return 5, queue is [4] qu.empty(); // return false |