放两个表情: 🐣🥚

1 用两个栈实现队列

像汉诺塔问题一般, 利用两个栈结构来颠倒栈内数据的顺序.

  1. class CQueue {
  2. Stack<Integer> in;
  3. Stack<Integer> out;
  4. public CQueue() {
  5. in = new Stack<>();
  6. out = new Stack<>();
  7. }
  8. public void appendTail(int value) {
  9. in.push(value);
  10. }
  11. public int deleteHead() {
  12. if (out.size() < 1) {
  13. if (in.size() < 1) {
  14. return -1;
  15. }
  16. in2Out();
  17. }
  18. return out.pop();
  19. }
  20. private void in2Out() {
  21. while(!in.isEmpty()) {
  22. out.push(in.pop());
  23. }
  24. }
  25. }

2 自定义栈结构 (带有min()方法)

思路: 自定义节点结构Node (val, min, next) 三个参数, val 表示当前值就不说了, min 这个参数就是典型的空间换时间了, 在每个节点上都存了一份目前为止的最小值, next 最重要的就这个参数, 它才保证了形成栈的结构, 它存放的是自身前一个进来的节点, 即上一个被压入栈中的元素.

  1. class MinStack {
  2. private Node topNode;
  3. /** initialize your data structure here. */
  4. public MinStack() { }
  5. public void push(int x) {
  6. if (topNode == null)
  7. topNode = new Node(x, x, null);
  8. else
  9. topNode = new Node(x, Math.min(x, topNode.val), topNode);
  10. }
  11. public void pop() {
  12. topNode = topNode.next;
  13. }
  14. public int top() {
  15. return topNode.val;
  16. }
  17. public int min() {
  18. return topNode.min;
  19. }
  20. // next 就相当于被压入栈底的旧节点
  21. private class Node {
  22. int val, min;
  23. Node next;
  24. public Node(int val, int min, Node next) {
  25. this.val = val;
  26. this.min = min;
  27. this.next = next;
  28. }
  29. }
  30. }