题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
时间限制:1秒 空间限制:32768K 热度指数:476721
解答:
import java.util.Stack;
//思路:将stack2当做入队列,将stack1当做出队列,
//当队列需要push入队列一个元素的时候,直接push到stack2就可以了;
//当队列需要pop出队列时,首先判断stack1是否为空,
//如果为空,则将stack2中的元素全部pop出来并依次push到stack1中,再让stack1来pop一下就可以了;
//如果不为空,stack1直接pop一下就行
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack2.push(node);
}
public int pop() {
if(stack1.size() == 0){
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
}
if(stack1.isEmpty()){
System.out.println("stack1 and stack2 is all empty");
return -1;
}
return stack1.pop();
}
}