The post Implement Queue Using 2 Stacks in Java appeared first on MooMetric.com.

]]>To begin, we will initialise 2 Stacks and name them “s1” and “s2”.

import java.util.Stack; public class QueueUsing2Stacks<E> { // Initialise stacks Stack<E> s1 = new Stack<E>(); Stack<E> s2 = new Stack<E>(); // Add to queue public void add(E val) { s1.push(val); } // Get size of queue public int size() { return s1.size() + s2.size(); } // Returns true if queue is empty public boolean empty() { if(s1.empty() && s2.empty()) { return true; } return false; } // Returns element at the front of queue public E peek() { if(!empty()) { if(s2.empty()) { while(!s1.empty()) { s2.push(s1.pop()); } } return s2.peek(); } return null; } // Removes and returns element at the front of queue public E remove() { if(!empty()) { if(s2.empty()) { while(!s1.empty()) { s2.push(s1.pop()); } } return s2.pop(); } return null; } }

** Add**Adds an element to the front of the queue. This is done simply by pushing the element onto “s1”.

** Size**Returns the number of elements currently in the queue. Adding the number of elements in “s1” and “s2” will give the total number of elements in the queue.

** Empty**Returns true if the queue is empty and false if it is not. We know the queue is empty if both “s1” and “s2” are empty as well.

** Peek**Returns element at the front of the queue without removing it from the queue. This can be achieved by first checking if the queue is empty and returning a null if it is. Otherwise, we will then proceed to check if there are any elements in “s2”. If there is an element in “s2”, we will simply return that element from the top of “s2” without removing it. If there aren’t any elements in “s2”, we will move all elements from “s1” to “s2” afterwhich we will return that element from the top of “s2” without removing it.

** Remove**Removes and returns element at the front of the queue. This can be achieved by first checking if the queue is empty and returning a null if it is. Otherwise, we will then proceed to check if there are any elements in “s2”.If there is an element in “s2”, we will simply remove and return that element from the top of “s2”. If there aren’t any elements in “s2”, we will move all elements from “s1” to “s2” afterwhich we will remove and return that element from the top of “s2”.

We can see how it works by looking at the following diagram. If we add 3 elements to the queue, they will be pushed onto “s1” as such:

Now, if we wanted to remove elements from the queue, we would first move them over to “s2” since “s2” is empty and then we would pop them out. Notice that the order of the elements has been reversed thus conforming to the First-In-First-Out (FIFO) requirements of a Queue structure.

Try out the code for yourself and see how it goes!

The post Implement Queue Using 2 Stacks in Java appeared first on MooMetric.com.

]]>