package Queue;
import stack.Dynamic_Stack;
import stack.StackUsingArray;
public class QUS_EnqueueEfficient {
public Dynamic_Stack primary;
public Dynamic_Stack secondary;
public QUS_EnqueueEfficient() throws Exception{
this.primary = new Dynamic_Stack();
this.secondary = new Dynamic_Stack();
}
public boolean isEmpty() {
return this.primary.isEmpty();
}
public int size() {
return this.primary.size();
}
public void enqueue(int data) throws Exception{
this.primary.push(data);
}
public int dequeue() throws Exception{
while(primary.size()!=1) {
secondary.push(this.primary.pop());
}
int rv = this.primary.pop();
while(!secondary.isEmpty()) {
primary.push(this.secondary.pop());
}
return rv;
}
public int getFront() throws Exception{
while(this.primary.size()!=1) {
this.secondary.push(this.primary.pop());
}
int rv = this.primary.peek();
secondary.push(rv);
while(this.secondary.isEmpty()) {
this.primary.push(this.secondary.pop());
}
return rv;
}
public static void reverse(Dynamic_Stack stack1,Dynamic_Stack stack2,int index) throws Exception{
if(stack1.isEmpty()) {
return;
}
int item = stack1.pop();
reverse(stack1,stack2,index+1);
stack2.push(item);
if(index==0) {
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
}
public void Display() throws Exception{
reverse(primary,secondary,0);
primary.display();
reverse(primary,secondary,0);
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
QUS_EnqueueEfficient queue = new QUS_EnqueueEfficient();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.Display();
System.out.println(queue.dequeue());
queue.Display();
System.out.println(queue.getFront());
queue.Display(); //Getting Wrong Output 30,20 ,20, END
System.out.println(queue.dequeue());
queue.Display();
System.out.println(queue.getFront());
}
}