Java栈(数组实现)

来源:互联网 发布:免费虚拟手机号软件 编辑:程序博客网 时间:2024/06/06 01:49
/** * 用数组实现栈,最主要的是要在类的内部定义一个数组, * 并且这个数组要具有一定的大小,要在定义栈的时候定义好 */public class ArrayStack{    private static final String TAG = "ArrayStack";    private Object[] contents;    private int top = -1;    private int bottom = -1;    private int SIZE = 10;//有一个初始值大小    public ArrayStack()    {        contents = new Object[SIZE];        top = -1;    }    public int push(Object obj) throws Exception    {        if (top > SIZE) throw new Exception("栈已经满了!");        top++;        contents[top] = obj;        return top;    }    public Object pop() throws Exception    {        if (top == bottom) throw new Exception("栈已经空了!");        Object obj = contents[top];        contents[top] = null;        top--;        return obj;    }    public boolean isEmpty()    {        return top == bottom;    }    public int getSize()    {        return top + 1;    }    public void display() throws Exception    {        if (getSize() == 0) throw new Exception("空栈!");        for (int i=getSize()-1;i>=0;i--)        {            System.out.print(contents[i].toString() + "->");        }        System.out.println("");    }    public static void main(String[] args) throws Exception    {        ArrayStack as = new ArrayStack();        //as.display();        as.push("你好");        as.push("q");        as.push("werewrwer");        as.push("weee");        as.push("we123");        as.push("ertte");        as.push("ggmt");        as.display();        as.pop();        System.out.println(as.getSize());        as.pop();        as.display();    }} 
0 0
原创粉丝点击