155. 最小栈

自己做
解:一栈一链表

class MinStack {public static class Node {public int val; // 存储的整数数据public Node next; // 指向下一个节点的引用// 节点构造方法public Node(int data) {this.val = data;this.next = null; // 初始无后续节点}}private Stack<Integer> s;private Node sort_list;public MinStack() {s = new Stack();sort_list = new Node(Integer.MIN_VALUE);}public void push(int val) {s.push(val);Node q = sort_list;Node p = sort_list.next;if(p == null)q.next = new Node(val);else{while(p != null && p.val < val){q = p;p = p.next;}q.next = new Node(val);q = q.next;q.next = p;}}public void pop() {int val = s.peek();s.pop();Node p = sort_list;while(p.next.val != val)p = p.next;p.next = p.next.next;}public int top() {return s.peek();}public int getMin() {return sort_list.next.val;}
}/*** Your MinStack object will be instantiated and called as such:* MinStack obj = new MinStack();* obj.push(val);* obj.pop();* int param_3 = obj.top();* int param_4 = obj.getMin();*/

看题解

class MinStack {Deque<Integer> xStack;Deque<Integer> minStack;public MinStack() {xStack = new LinkedList<Integer>();minStack = new LinkedList<Integer>();minStack.push(Integer.MAX_VALUE);}public void push(int x) {xStack.push(x);minStack.push(Math.min(minStack.peek(), x));}public void pop() {xStack.pop();minStack.pop();}public int top() {return xStack.peek();}public int getMin() {return minStack.peek();}
}作者:力扣官方题解
链接:https://leetcode.cn/problems/min-stack/solutions/242190/zui-xiao-zhan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。