高级程序设计01

1、 修改程序清单19-1中的GenerisStack类,使用数组而不是ArrayList来实现它。需要在给栈添加新元素之前检查数组的大小。如果数组满了,则创建一个新数组,该数组容量是原先数组容量的两倍,然后将当前数组的元素复制到新数组当中。

 

package zlc;

public class Stack<E> {
    E[] a;
    int cnt;
    int top;
    public Stack () {
        cnt=1010;
        top=0;
        a=(E[])new Object[cnt];
    }
    public int getSize () {
        return top;
    }
    public E peek () {
        return a[top-1];
    }
    public void push (E x) {
        if (top==cnt) {
            E[] b=(E[])new Object[cnt<<1];
            for (int i=0;i<cnt;i++) b[i]=a[i];
            top=0;
        }
        a[top++]=x;
    }
    public E pop () {
        E x=a[top-1];
        top--;
        return x;
    }
    public boolean isEmpty () {
        return top==0?true:false;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Stack<String> st=new Stack<>();
        st.push("1");
        System.out.println(st.peek());
    }

}

 

posted @ 2020-09-30 16:31  zlc0405  阅读(469)  评论(1编辑  收藏  举报