描述: 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:栈是“先进后出”而队列是“先进先出”
1.push时,直接插入到栈1中;
2.pop时,如果栈2不为空,直接弹出栈2栈顶元素;如果为空,先将栈1元素逐个出栈再入栈进栈2中,再弹出栈2栈顶元素。
复杂度:均为O(1)
代码:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
//push
public void push(int i){
stack1.push(i);
}
//pop
public int pop(){
if(stack2.size<=0){
while(stack1.size!=0){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}