two stack for a queue

points: stack is First In Last Out while queue is First In First Out.

stack1 used for push, stack2 used for pop.

if we push a, b, c in stack1, when we pop, we push every element into stack2 for pop.

when new element comes in, still use stack1 for push. when pop, if stack2 is empty, push it with elements in stack1.

class Queue{

private Stack s1;

private Stack s2;

public Queue(Stack s1, Stack s2){

this.s1 = s1;

this.s2 = s2

}

public Type<T> appendTail(Type <T> t){

s1.push(t);

}

public Type<T> deleteHead(){

if(s2.size()==0){

Type<T> t=null;

while(s1.size>0){

t=s1.top();

s1.pop();

s2.puch(t);

}

}

if(s2.size()==0){

throw new exception(“emptyQueue”);

}

Type<T> head = s2.top();

s2.pop();

return head;

}

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s