算法总结之 栈和队列

实现一个特殊的栈,在实现栈的基本功能基础上,再实现返回栈中最小元素的操作。

 

思路: 

 在设计上 使用两个栈,一个用来保存当前栈中的元素,其功能和一个正常的栈没有区别。记为 stackData

另一个栈用来保存每一步的最小值,这个栈记为 stakMin

 

压入数据规则:

 假设当前数据为 newNum 先将其压入 stackData  然后判断stackMin是否为空

     如果空  newNum也压入stackMin

    如果不空 比较newNum和stackMin 的栈顶元素哪个更小

    如果 newNum <= stackMin,peek() 则newNum 也压入stackMin

    如果newNum > stackMin.peek() 则stackMin不压入任何内容

 

弹出数据规则

  先在stackData 弹出栈顶元素,记value  然后比较当前stackMin 的栈顶元素和value 哪个更小

当value等于stackMin的栈顶元素时,stackMin弹出栈顶元素, 

当value大于stackMin的栈顶元素时, stackMin不弹出元素 返回value

 

查询当前栈中的最小值操作

  stackMin中始终记录着stackData中的最小,所以stackMin的栈顶元素市中市当前stackData中的最小值

package TT;

import java.util.Stack;

public class Test120 {

public class Mystack1{
    
 private Stack<Integer> stackData;
 private Stack<Integer> stackMin;
 
 public Mystack1(){
     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 <= this.getmin()){
         this.stackMin.push(newNum);
     }
     this.stackData.push(newNum);
     
 }
public int pop(){
    
    if(this.stackData.isEmpty()){
        throw new RuntimeException("your stack is empty");
    }
    int value = this.stackData.pop();
    if(value == this.getmin()){
        this.stackMin.pop();
    }
    return value;
}    
    
    public int getmin(){
        if(this.stackMin.isEmpty()){
            throw new RuntimeException("your stack is empty");
        }
      return this.stackMin.peek();
    }
}
}

 

posted @ 2017-09-12 15:04  toov5  阅读(168)  评论(0编辑  收藏  举报