题目:用两个栈模拟一个队列。实现push,pop方法。
分析:栈的特点:先进后出
队列的特点:先进先出,后进后出,队尾进,队头出。
图示:
入队:默认储存在stack1中.
出队:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node)
stack1.push(node);//入队的默认放入栈1中
}
public int pop() {
if (stack2.empty()){//如果栈2等于空,那么将栈1 的元素放入栈2中
while (!stack1.empty()){//while循环为了把栈1的元素全部放入栈2 中,否则会破坏顺序。
stack2.push(stack1.pop());
}
}
return stack2.pop();//栈2不为空,直接移除栈2顶元素,并作为返回值
}
}