Saturday, 11 August 2018

Implement Queue Using 2 Stacks in Java programming





Today, we will take a gander at how we can actualize a Queue by utilizing 2 Stacks in Java. Note that a Queue is an interface in Java and to accurately actualize it completely as per the documentation, the majority of its strategy marks must be superseded. For this situation be that as it may, we are actualizing a Queue utilizing our own custom strategies and thusly, we have overlooked the "executes Queue" watchword from the class name. Don't hesitate to add individually techniques also in the event that you require!

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.

0 comments:

Post a Comment