/*实现一个特殊栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作
* 要求:1.pop,push,getMain操作的时间复杂度为O(1);
* 2.设计的栈类型使用现成栈结构
*
* 准备两个栈,Data、min
* min随着Data增长
* 1.当Data压入4,min也压入4(Data压入什么数字min就压入什么数字)
* 2.但是当Data压入5时,*************比较:Data当前的数字与min栈顶数比较,min小,
* min则继续压入4,如果压入的是3,与min比较,Data中的数字比min中栈顶的元素小,则min栈压入3
* 以此类推。
*
* Data正常压栈,min压入小的数字,如果一样大,持续压入原先的数字。每次压栈都要比较;min栈栈底则为最小元素。
* 当弹出数字时,min随着Data弹出。*/
代码如下:
1 public class Bokeyuan { 2 public static class MyStack1{ 3 private Stack<Integer> stackData; 4 private Stack<Integer> stackMin; 5 6 public MyStack1() { 7 this.stackData=new Stack<Integer>(); 8 this.stackMin=new Stack<Integer>(); 9 } 10 11 public void push (int newNum) { 12 if(this.stackMin.isEmpty()) { 13 this.stackMin.push(newNum); 14 }else if(newNum<=this.getMin()) { 15 this.stackMin.push(newNum); 16 } 17 this.stackData.push(newNum); 18 } 19 20 private int getMin() { 21 // TODO 自动生成的方法存根 22 if(this.stackMin.isEmpty()) { 23 throw new RuntimeException("You stack is empty"); 24 } 25 return this.stackMin.peek(); 26 } 27 28 public int pop() { 29 if(this.stackData.isEmpty()) { 30 throw new RuntimeException("You stack is empty"); 31 } 32 int value=this.stackData.pop(); 33 if(value==this.getMin()) { 34 this.stackMin.pop(); 35 } 36 return value; 37 } 38 } 39 40 41 //第二种方法 42 public static class MyStack2{ 43 private Stack<Integer> stackData;//Data栈 44 private Stack<Integer> stackMin;//Min栈 45 46 public MyStack2() { 47 this.stackData=new Stack<Integer>();//系统提供的栈结构 48 this.stackMin=new Stack<Integer>(); 49 } 50 51 public void push(int newNum) {//最小栈更新 52 if(this.stackMin.isEmpty()) {//当最小栈空 53 this.stackMin.push(newNum);//压入最小值 54 }else if(newNum<this.getMin()) {//当新进的数比min栈顶小 55 this.stackMin.push(newNum);//压入当前数 56 }else { 57 int newMin=this.stackMin.peek();//当min栈顶数值更小 58 this.stackMin.push(newNum);//重复压入min栈顶最小值 59 } 60 this.stackData.push(newNum);//Data栈压入新数 61 } 62 63 private int getMin() {//min栈栈顶操作 64 // TODO 自动生成的方法存根 65 if(this.stackMin.isEmpty()) { 66 throw new RuntimeException("You stack is empty"); 67 } 68 return this.stackMin.peek();//peek()返回栈顶不弹出操作 69 } 70 71 public int pop() {//为空 报错 72 if(this.stackData.isEmpty()) { 73 throw new RuntimeException("You stack is empty"); 74 } 75 this.stackMin.pop();//否则min弹出 76 return this.stackData.pop();//Data弹出 77 } 78 } 79 80 //测试 81 public static void main(String[] args) { 82 MyStack1 stack1 = new MyStack1(); 83 stack1.push(3); 84 System.out.println(stack1.getMin()); 85 stack1.push(4); 86 System.out.println(stack1.getMin()); 87 stack1.push(1); 88 System.out.println(stack1.getMin()); 89 System.out.println(stack1.pop()); 90 System.out.println(stack1.getMin()); 91 92 System.out.println("============="); 93 94 MyStack1 stack2 = new MyStack1(); 95 stack2.push(3); 96 System.out.println(stack2.getMin()); 97 stack2.push(4); 98 System.out.println(stack2.getMin()); 99 stack2.push(1); 100 System.out.println(stack2.getMin()); 101 System.out.println(stack2.pop()); 102 System.out.println(stack2.getMin()); 103 } 104 }