题目列表

  • 232. 用栈实现队列
  • 155. 最小栈

    具体做法

    232. 用栈实现队列

    1. class MyQueue {
    2. private Stack<Integer> stk1;
    3. private Stack<Integer> stk2;
    4. public MyQueue() {
    5. stk1 = new Stack<>();
    6. stk2 = new Stack<>();
    7. }
    8. public void push(int x) {
    9. stk1.push(x);
    10. }
    11. public int pop() {
    12. if(!stk2.isEmpty()) return stk2.pop();
    13. if(stk1.isEmpty()) return -1;
    14. while(!stk1.isEmpty()){
    15. stk2.push(stk1.pop());
    16. }
    17. return stk2.pop();
    18. }
    19. public int peek() {
    20. if(!stk2.isEmpty()) return stk2.peek();
    21. if(stk1.isEmpty()) return -1;
    22. while(!stk1.isEmpty()){
    23. stk2.push(stk1.pop());
    24. }
    25. return stk2.peek();
    26. }
    27. public boolean empty() {
    28. return stk2.isEmpty()&&stk1.isEmpty();
    29. }
    30. }

    155. 最小栈

    1. class MinStack {
    2. Stack<Integer> stk1;
    3. Stack<Integer> stk2;
    4. public MinStack() {
    5. stk1 = new Stack<>();
    6. stk2 = new Stack<>();
    7. }
    8. public void push(int val) {
    9. stk1.push(val);
    10. if(stk2.isEmpty()){
    11. stk2.push(val);
    12. }else{
    13. if(val <= stk2.peek()) stk2.push(val);
    14. }
    15. }
    16. public void pop() {
    17. int x = stk1.pop();
    18. if(x == stk2.peek()) stk2.pop();
    19. }
    20. public int top() {
    21. return stk1.peek();
    22. }
    23. public int getMin() {
    24. return stk2.peek();
    25. }
    26. }