Showing posts with label Implement Stack using two Queues in Java. Show all posts
Showing posts with label Implement Stack using two Queues in Java. Show all posts

Sunday, March 23, 2014

Implement Stack using two Queues in Java

Please go through the below program to understand the code 



package test.sachi.dsnalgos;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

/*
 * Create two queues : 'q' and 'tmpq' as in the program given below
 For push operation :
 if size of q = 0 then
 enqueue value into q
 else
 dequeue all elements from q to tmpq
 enqueue value into q
 dequeue all elements from tmpq to q

 For pop operation :
 if size of q = 0 then
 throw 'underflow' exception
 else 
 return front element of q

 */

public class StackUsingTwoQueues {

Queue<Integer> q;
Queue<Integer> tempq;

// contructor
public StackUsingTwoQueues() {
q = new LinkedList<Integer>();
tempq = new LinkedList<Integer>();
}

// Method to push the element to the Stack

public void push(int data) {

if (q.size() == 0) {
q.add(data);
} else {
int l = q.size();
for (int i = 0; i < l; i++) {
tempq.add(q.remove());
}
q.add(data);
for (int i = 0; i < l; i++) {
q.add(tempq.remove());
}
}

}

public int pop() throws Exception {
if (q.size() == 0) {
throw new NoSuchElementException("Underflow Exception");
}

return q.remove();
}

public int peek() throws Exception {

if (q.size() == 0) {
throw new NoSuchElementException("Underflow Exception");
}

return q.peek();
}
public boolean isEmpty(){
if(q.size()==0){
return true;
}else{
return false;
}
}
public int getSize(){
return q.size();
}
public void display(){
System.out.print("\nStack = ");
        int l = getSize();
        if (l == 0)
            System.out.print("Empty\n");
        else
        {
            Iterator<Integer> it = q.iterator();
            while (it.hasNext())
                System.out.print(it.next()+" ");
            System.out.println();
        }
}


}