import java.util.LinkedList;
// 使用链表实现栈操作
public class MyStack {
public static void main(String[] args) {
MyStack stack = new MyStack(5);
int[] arr = {2, 5, 7, 8, 9, 0};
for (int n : arr) {
NodeStack node = new NodeStack();
node.v = n;
stack.push(node);
}
System.out.println(stack.min);
System.out.println(stack.max);
NodeStack n1 = stack.pop();
System.out.println("v1=" + n1.v);
System.out.println(stack.min);
System.out.println(stack.max);
NodeStack n2 = stack.pop();
System.out.println("v2=" + n2.v);
NodeStack n3 = stack.pop();
System.out.println("v3=" + n3.v);
System.out.println(stack.min);
System.out.println(stack.max);
NodeStack n4 = stack.pop();
System.out.println("v4=" + n4.v);
System.out.println(stack.min);
System.out.println(stack.max);
NodeStack n5 = stack.pop();
System.out.println("v5=" + n5.v);
System.out.println(stack.min);
System.out.println(stack.max);
stack.pop();
System.out.println();
}
public LinkedList<NodeStack> list = null;
private int size;
public MyStack(int size) {
this.size = size;
list = new LinkedList<NodeStack>();
}
private int min = Integer.MAX_VALUE;
private int max = Integer.MIN_VALUE;
public void push(NodeStack node) {
if (this.list.size() < this.size) {
this.list.add(0, node);
getMaxMin(node);
} else {
System.out.println("stack is full");
}
}
public NodeStack pop() {
if (this.list.size() > 0) {
NodeStack node = this.list.get(0);
this.list.remove(0);
if (this.list.isEmpty()) {
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
} else if (node.v == min) {
min = min().v;
} else if (node.v == max) {
max = max().v;
}
return node;
} else {
System.out.println("stack is empty");
}
return null;
}
public void getMaxMin(NodeStack node) {
if (min > node.v) {
min = node.v;
}
if (max < node.v) {
max = node.v;
}
}
public NodeStack min() {
min = Integer.MAX_VALUE;
NodeStack nodeMin = null;
for (NodeStack node : this.list) {
if (node.v < min) {
min = node.v;
nodeMin = node;
}
}
return nodeMin;
}
public NodeStack max() {
max = Integer.MIN_VALUE;
NodeStack nodeMin = null;
for (NodeStack node : this.list) {
if (node.v > max) {
max = node.v;
nodeMin = node;
}
}
return nodeMin;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}
class NodeStack {
public int v;
}