【剑指offer】队列和栈的互相实现

时间:2022-06-05 17:40:06

队列先进先出,栈先进后出。
两个栈实现队列

public class StackToQueue<T> {
Stack<T> stack1=new Stack<T>();
Stack<T> stack2=new Stack<T>();

public void push(T t){
stack1.push(t);
}

public T pop(){
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}

两个队列实现栈

public class QueueToStack<T> {
private Queue<T> queue1=new LinkedList<T>();
private Queue<T> queue2=new LinkedList<T>();

public void push(T t){
queue1.add(t);
}
public T pop(){
if(!queue1.isEmpty()){
while(queue1.size()>1){
queue2.add(queue1.remove());
}
return queue1.remove();
}else{
while(queue2.size()>1){
queue1.add(queue2.remove());
}
return queue2.remove();
}
}
}