放两个表情: 🐣🥚
1 用两个栈实现队列
像汉诺塔问题一般, 利用两个栈结构来颠倒栈内数据的顺序.
class CQueue {Stack<Integer> in;Stack<Integer> out;public CQueue() {in = new Stack<>();out = new Stack<>();}public void appendTail(int value) {in.push(value);}public int deleteHead() {if (out.size() < 1) {if (in.size() < 1) {return -1;}in2Out();}return out.pop();}private void in2Out() {while(!in.isEmpty()) {out.push(in.pop());}}}
2 自定义栈结构 (带有min()方法)
思路: 自定义节点结构Node (val, min, next) 三个参数, val 表示当前值就不说了, min 这个参数就是典型的空间换时间了, 在每个节点上都存了一份目前为止的最小值, next 最重要的就这个参数, 它才保证了形成栈的结构, 它存放的是自身前一个进来的节点, 即上一个被压入栈中的元素.
class MinStack {private Node topNode;/** initialize your data structure here. */public MinStack() { }public void push(int x) {if (topNode == null)topNode = new Node(x, x, null);elsetopNode = new Node(x, Math.min(x, topNode.val), topNode);}public void pop() {topNode = topNode.next;}public int top() {return topNode.val;}public int min() {return topNode.min;}// next 就相当于被压入栈底的旧节点private class Node {int val, min;Node next;public Node(int val, int min, Node next) {this.val = val;this.min = min;this.next = next;}}}
