题目
用两个栈来实现一个队列,完成队列的push
和pop
操作。
思路
队列的性质就是先进先出,那么可以把所有元素压如stack1
中,取数据的时候,如果stack2
为空,就把stack
中的数据取出压入stack2
中,这样最早加入stack1
中的数据就在stack2
的最上面,直接pop
即可。
实现
public class Solution {
Stack<Object> stack1 = new Stack<>();
Stack<Object> stack2 = new Stack<>();
public static void main(String[] args) {
Solution solution = new Solution();
for (int i = 0; i < 8; i++) {
solution.push(i);
}
for (int i = 0; i < 8; i++) {
System.out.println(solution.pop());
}
}
public void push(Object value) {
stack1.push(value);
}
public Object pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}