BM42 用两个栈实现队列
描述
用两个栈来实现一个队列,使用n个元素来完成 n 次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
数据范围: n\le1000n≤1000
要求:存储n个元素的空间复杂度为 O(n)O(n) ,插入与删除的时间复杂度都是 O(1)O(1)
示例1
输入:
["PSH1","PSH2","POP","POP"]
返回值:
1,2
示例2
输入:
["PSH2","POP","PSH1","POP"]
返回值:
2,1
解法
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack();
Stack<Integer> stack2 = new Stack();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack2.size() <= 0) {
while (stack1.size() != 0) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
posted on 2022-09-22 23:49 somedieyoung-navi 阅读(29) 评论(0) 编辑 收藏 举报