import java.util.Stack;
/**
* 〈一句话功能简述〉<br>
* 〈设计一个特殊栈,实现返回最小值push,pop,getmin时间复杂度都为O(1)〉
*
* @author Administrator
* @create 2019/6/2
* @since 1.0.0
*/
public class GetStackMin {
public static class StackArr1 {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public StackArr1() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void Push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum < GetMin()) {
this.stackMin.push(newNum);
} else {
newNum = GetMin();
this.stackMin.push(newNum);
}
this.stackData.push(newNum);
}
public int Pop() {
if (this.stackData.isEmpty()) {//min栈是跟随Data栈往外弹,所以这里判定data栈是否为空
throw new RuntimeException("the stack is empty");
}
this.stackMin.pop();
return this.stackData.pop();
}
public Integer GetMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("the stack is empty");
}
return this.stackMin.peek();
}
}
public static class StackArr2 {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public StackArr2() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void Push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum <= GetMin()) {
this.stackMin.push(newNum);
}
this.stackData.push(newNum);
}
public int Pop() {
if (this.stackData.isEmpty()) {//min栈是跟随Data栈往外弹,所以这里判定data栈是否为空
throw new RuntimeException("the stack is empty");
}
int res = this.stackData.pop();
if (res == GetMin()) {//这与第一种方法不同,Min栈只弹与Data栈相等的数
this.stackMin.pop();
}
return res;
}
public Integer GetMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("the stack is empty");
}
return this.stackMin.peek();
}
}
public static void main(String[] args) {
StackArr1 stack1 = new StackArr1();
//stack1.StackArr1();
stack1.Push(3);
System.out.println(stack1.GetMin());
stack1.Push(4);
System.out.println(stack1.GetMin());
stack1.Push(1);
System.out.println(stack1.GetMin());
System.out.println(stack1.Pop());
System.out.println(stack1.GetMin());
System.out.println("=============");
StackArr2 stack2 = new StackArr2();
//stack2.StackArr2();
stack2.Push(3);
System.out.println(stack2.GetMin());
stack2.Push(4);
System.out.println(stack2.GetMin());
stack2.Push(1);
System.out.println(stack2.GetMin());
System.out.println(stack2.Pop());
System.out.println(stack2.GetMin());
}
}
代码没什么可说的,只是注意,JAVA是有构造函数一说的,用于给对象初始化。