java 栈 【1】

参考:http://kevin-in-java.iteye.com/blog/1223149

定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都是O(1)。

核心思想:添加辅助栈,将最小值也添加到辅助栈,出栈时,如果是最小值,辅助栈也要出栈。

备注:此处采用顺序栈,无法扩大存储面积,可参考链接日志采用链栈;

          出栈的数据类型采用Integer考虑到可能出栈不成功,int无法满足,则以NULL表示无法出栈成功

   要注意Integer和int的转换问题。 以及Integer.valueOf(int i), integer.equals(int i)

另外:程序一定要测试啊,不要想当然认为小程序就是对的!惨痛的教训

//辅助类
/**
 * Copyright 2013
 * @author Xie Yifeng
 * Created on 2013 2013-3-22
 */
package xyf.second;

/**
 *  辅助栈
 */
public class AssistStack {
    final int maxSize = 100;
    private int[] data;
    private int top;
    
    public AssistStack(){
        data = new int[maxSize];
        top = -1;
    }
    public int getTop(){
        return top;
    }
    
    public void push(int a){
        if(top>=maxSize-1)
            return;
        data[++top] = a;
    }
    
    public Integer pop(){
        Integer temp = null;
        if(top<0)
            return null;
        temp = Integer.valueOf(data[top--]);
        return temp;
    }
    
    public Integer getPos(){
        Integer temp = null;
        if(top<0)
            return null;
        temp = Integer.valueOf(data[top]);
        return temp;
    }
}
//栈
/**
 * Copyright 2013
 * @author Xie Yifeng
 * Created on 2013 2013-3-22
 */
package xyf.second;

/**
 *
 */
public class MyStack {
    final int maxSize = 100;
    private AssistStack asStack;
    private int[] data;
    private int top;
    
    
    public MyStack(){
        asStack = new AssistStack();
        data = new int[maxSize];
        top = -1;
    }
    
    
    public void push(int a ){
        if(top>=maxSize-1)
            return;
        data[++top]= a;
        if(top==0)
            asStack.push(a);
        else{
            if(a<=asStack.getPos())
                asStack.push(a);
        }
    }
    
    public Integer pop(){
        Integer temp;
        if(top<0)
            return null;
        if(asStack.getPos().equals(data[top]))
            asStack.pop();
        temp = Integer.valueOf(data[top--]);
        return temp;
    }
    
    public Integer Min(){
        if(top<0)
            return null;
        else return asStack.getPos();
    }
    
    public boolean hasNext(){
        if(top>=0)
            return true;
        else return false;
    }
    
    public static void main(String[] args){
        MyStack my = new MyStack();
        int[] table =  new int[5];
        int i =0;
        for(;i<5;i++){
            table[i] = (int)(Math.random()*100);
            System.out.println(table[i]);
            my.push(table[i]);
        }
        System.out.println("最小值:"+my.Min());
        System.out.println("最小值:"+my.Min());
        while(my.hasNext()){
            
            System.out.println("输出:"+my.pop()+ " 最小值:" + my.Min());
        }
    }
}

源代码在文件: java栈Min中

原文地址:https://www.cnblogs.com/nkxyf/p/2976482.html