8.5:实现特殊栈,在基本功能的基础上,再实现返回栈中最小元素的功能

8.5:实现特殊栈,在基本功能的基础上,再实现返回栈中最小元素的功能

 

  1、pop,push,getMin操作的时间复杂度是o(1)。

 

  2、设计的栈类型可以使用现成的栈结构。

  

  两个栈,一个数据栈,一个最小栈。每次数据过来压入数据组,同时压入最小栈,但压入最小

栈是有条件的:

  1、如果最小栈中没有数,压入;

  2、如果当前数比栈顶数小,放当前数;如果当前数比栈顶数大,重复放入栈顶数;

  3、数据栈和最小栈同步增长。

       弹出数据栈里的数,同步弹出对应的最小栈里的数。

 

 1 public static class MyStack1 {
 2         private Stack<Integer> stackData;
 3         private Stack<Integer> stackMin;
 4 
 5         public MyStack1() {
 6             this.stackData = new Stack<Integer>();
 7             this.stackMin = new Stack<Integer>();
 8         }
 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         //出栈
21         public int pop() {
22             if (this.stackData.isEmpty()) {
23                 throw new RuntimeException("Your stack is empty.");
24             }
25             int value = this.stackData.pop();    // 1、数据栈,栈顶元素出
26             if (value == this.getmin()) {
27                 this.stackMin.pop();             // 2.1、数据栈的栈顶元素和最小栈的栈顶元素一致,最小栈,栈顶元素出
28             }
29             return value;                        // 2.2、数据栈的栈顶元素和最小栈的栈顶元素不一致,最小栈,栈顶元素出
30         }
31 
32         
33         public int getmin() {
34             if (this.stackMin.isEmpty()) {
35                 throw new RuntimeException("Your stack is empty.");
36             }
37             return this.stackMin.peek();         //获取的是:当前最小栈的栈顶元素。
38         }
39     }

 

 

 

 

posted @ 2022-05-09 14:18  yzmarcus  阅读(34)  评论(0)    收藏  举报