public class Queue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Queue() {
stack1=new Stack<Integer>();
stack2=new Stack<Integer>();
}
public void push(int element) {
if(stack1.empty()){
int t;
while(!stack2.empty()){
t=stack2.pop();
stack1.push(t);
}
}
stack1.push(element);
}
public int pop() {
if(stack2.empty()){
int t;
while(!stack1.empty()){
t=stack1.pop();
stack2.push(t);
}
}
return stack2.pop();
}
public int top() {//top()返回队列头元素
int t;
if(!stack2.empty()){
t=stack2.pop();
stack2.push(t);
return t;
}else{
while(!stack1.empty()){
t=stack1.pop();
stack2.push(t);
}
t=stack2.pop();
stack2.push(t);
return t;
}
}
}
主要思想:
采用两个栈:
stack1用来执行入栈操作;stack2用来执行出栈操作
入栈时,先判断stack1是否为空,如果为空,且stack2有元素,将stack2元素依次出栈并push到stack1中;stack1再执行入栈(及队列入队)操作。
出栈时,先判断stack2是否为空,如果为空,且stack1有元素,将stack1元素依次出栈并push到stack2中;stach2再执行出栈(及队列出队)操作。