Tuesday, October 02, 2007

Implementing a queue with 2 Stacks

Interesting, but intuitive question.

My Solution:-

//QueueWith2Stacks.java

import java.util.Stack;

public class QueueWith2Stacks {

Stack< Object> insertStack=new Stack< Object>();
Stack< Object> popStack=new Stack< Object>();


void enqueue(Object element){
insertStack.push(element);
}
Object dequeue(){
if(popStack.empty()&& insertStack.empty())
return(null);
if(popStack.empty())//This is the only interesting part about it.
while(!insertStack.empty())
popStack.push(insertStack.pop());
return(popStack.pop());
}
void display(){
System.out.println(popStack.toString()+insertStack.toString());
}
}

4 comments:

maye said...

This is really usefull. Well done, Thanks

Elizabeth said...

Thanks, this was super helpful. :)

Nelson said...

Good work.

Nelson said...

Hope to learn programming tech. like you have.......Great help!