题目列表
- 232. 用栈实现队列
-
具体做法
232. 用栈实现队列
class MyQueue {private Stack<Integer> stk1;private Stack<Integer> stk2;public MyQueue() {stk1 = new Stack<>();stk2 = new Stack<>();}public void push(int x) {stk1.push(x);}public int pop() {if(!stk2.isEmpty()) return stk2.pop();if(stk1.isEmpty()) return -1;while(!stk1.isEmpty()){stk2.push(stk1.pop());}return stk2.pop();}public int peek() {if(!stk2.isEmpty()) return stk2.peek();if(stk1.isEmpty()) return -1;while(!stk1.isEmpty()){stk2.push(stk1.pop());}return stk2.peek();}public boolean empty() {return stk2.isEmpty()&&stk1.isEmpty();}}
155. 最小栈
class MinStack {Stack<Integer> stk1;Stack<Integer> stk2;public MinStack() {stk1 = new Stack<>();stk2 = new Stack<>();}public void push(int val) {stk1.push(val);if(stk2.isEmpty()){stk2.push(val);}else{if(val <= stk2.peek()) stk2.push(val);}}public void pop() {int x = stk1.pop();if(x == stk2.peek()) stk2.pop();}public int top() {return stk1.peek();}public int getMin() {return stk2.peek();}}
