题解 | #包含min函数的栈#
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
import java.util.Stack;
public class Solution {
private Node head;
/** initialize your data structure here. */
public Solution() {
head = new Node(0, Integer.MAX_VALUE, null);
}
public void push(int x) {
// 头插法
head = new Node(x, Math.min(x, head.min), head);
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int min() {
// 获取头部最小值
return head.min;
}
private class Node {
// 存储的数据值
public int val;
// 最小值
public int min;
// 下一个节点
public Node next;
// 初始化
public Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
}
解题思想:通过结点储存压入的数值,头插法最小结点在第一个。
#算法##算法笔记#
查看7道真题和解析
