从逻辑结构上来说,栈是只允许在一端进行操作的线性结构;
从存储结构上来说,栈的实现既可以采用顺序存储方式,也可以采用链式存储方式;
以下是栈的链式存储方式实现:
public class Stack {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(-2);
stack.push(0);
stack.push(-3);
System.out.print(stack.getMin());
stack.pop();
System.out.print(stack.peek());
System.out.print(stack.getMin());
}
// 指向栈顶的指针
public Node top;
public Integer total;
// 结点类
public class Node {
public Integer val;
public Node next;
}
public Stack() {
this.top = null;
this.total = 0;
}
public boolean isEmpty() {
return this.top==null;
}
public void push(Integer val) {
Node node = new Node();
node.val = val;
// 插入头位置
node.next = this.top;// 当前栈顶结点成为新节点的下一位
this.top = node;// 更新栈顶结点
this.total++;
}
public void pop() {
if(isEmpty()) return;
Node neNode = this.top;
this.top = this.top.next;
this.total--;
}
public Integer peek() {
if(isEmpty())return null;
return this.top.val;
}
public Integer getMin() {
if(isEmpty()) return null;
Node node = this.top;
int minVal = node.val;
while(node!=null) {
minVal=minVal>node.val?node.val:minVal;
node=node.next;
}
return minVal;
}
}



