这题我在同花顺笔试里遇到过
栈是LIFO形式的,后进先出,总是弹栈顶的。
队列是FIFO形式的,先进先出,总是出队尾。
有两个栈,就可以倒腾一遍嘛,两次后进先出(将原来的栈顶元素置于栈底了),不就模拟了先进先出。
import java.util.Stack;
import java.util.stream.IntStream;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.isEmpty()&&stack2.isEmpty()){
throw new RuntimeException("队列空!");
}
if(stack2.isEmpty()) {
int n = stack1.size();
IntStream.range(0, n).forEach(i -> stack2.push(stack1.pop()));
}
return stack2.pop();
}
public static void main(String[] args) {
Solution s = new Solution();
IntStream.iterate(1,i->i+1).limit(5).forEach(s::push);
IntStream.iterate(1,i->i+1).limit(5).forEach(i->System.out.println("POp"+s.pop()));
}
}