日期:2014-05-20  浏览次数:20724 次

一道笔试题,麻烦大家看哈!
1)用int数组实现栈,实现pop(),push()方法,并且当栈空间满时,栈的空间增加一倍。
  2)在1)的基础之上,增加一个getMax()方法,返回栈中的最大值,要求这个函数具有O(1)的时间复杂度

------解决方案--------------------
http://topic.csdn.net/u/20090612/10/c1df5a00-ed6d-4c25-9b62-1b6507a55f7c.html


Java code
/*自己定义的栈,为了可以自由的访问栈中的元素。
 * */
class MyStack{
    String[]  st=new String[10];
    int top=0;
    void push(String vex){
        if(top==st.length-1){      //栈满时,给栈扩容
            String[] st1=new String[st.length+10];
            System.arraycopy(st, 0, st1, 0, st.length-1);
            st=st1;
        }
        st[top++]=vex;
    }
    boolean isEmpty() {
        if(top==0) return true;
        return false;
    }
    String pop(){
        if(top==0){
            return null;
        }else{
            return st[--top];    
        }
    }
    public String toString(){
        String s="";
        for(int i=0;i<top;i++){
            s=s+st[i]+" ";
        }
        return s;
    }
}