题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
牛客网练习地址
lc-jz
lc-232
实现
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) { //直接push到1
stack1.push(node);
}
public int pop() {
int elem;
if(stack2.isEmpty()){ //2为空,将1全部搬过来
while(!stack1.isEmpty()){
stack2.push(stack1.peek());
stack1.pop();
}
}
elem=stack2.peek(); //然后从2中pop出栈
stack2.pop();
return elem;
}
}