栈代码简单实现 [JAVA]

package com.free;

public class Stack<E>  {
    private Object[] data = null;

    private int maxSize = 0; // 栈的容量

    private int top = -1; // 栈顶的指针

    // 构造函数:根据指定的size初始化栈

    Stack() {
        this(10);
    }

    Stack(int initialSize) {
        if (initialSize >= 0) {
            this.maxSize = initialSize;
            this.data = new Object[initialSize];
            this.top = -1;
        } else {
            throw new RuntimeException("初始化大小不能为0:" + initialSize);
        }
    }

    /**
     * 向栈中压入一个数据,先入栈的数据在最下面
     *
     *
     * @param e
     * @return
     */
    public boolean push(E e) {
        if (top == maxSize - 1) {
            throw new RuntimeException("栈已满,无法将元素入栈");
        } else {
            data[++top] = e;
            return true;
        }
    }

    /**
     * 弹出栈顶数据,既移除栈顶数据
     * @return
     */
    public E pop() {
        if (top == -1) {
            throw new RuntimeException("栈为空!");
        } else {
            return (E) data[top--];
        }
    }

    /**
     * 返回当前的栈顶数据
     * @return
     */
    public E peek() {
        if (top == -1) {
            throw new RuntimeException("栈为空!");
        }

        return (E) data[top];
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容