栈(Java数组实现)


/**
 * 用数组实现栈,最主要的是要在类的内部定义一个数组,
 * 并且这个数组要具有一定的大小,要在定义栈的时候定义好
 */
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();

    }


} 
posted @ 2016-09-09 21:58  带妳心菲  阅读(260)  评论(0编辑  收藏  举报
Live2D
jQuery火箭图标返回顶部代码