栈的简易手写实现

直接上代码

package com.mydemo.writeCases;

/**
 * 简易栈手写实现
 * @param <E>
 */
public class IStack<E> {

    private E[] elemetData;
    private int size;

    public IStack(){
        this(5);
    }
    public IStack(int capacity){
        this.elemetData = (E[]) new Object[capacity];
    }

    /**
     * 获取元素个数
     * @return
     */
    public int getSize(){
        return this.size;
    }

    /**
     * 压栈
     * @param e
     */
    public void push(E e){
        //判断空间是否足够
        if (size == elemetData.length) {
            //扩容
            resize();
        }
        //添加到尾部
        elemetData[size] = e;
        size++;
    }

    /**
     * 出栈
     * @return
     */
    public E pop(){
        if (isEmpty()){
            throw new RuntimeException("栈为空");
        }
        E target = elemetData[size - 1];
        elemetData[size - 1] = null;
        size--;
        return target;
    }

    /**
     * 获取栈顶元素
     * @return
     */
    public E peek(){
        if (isEmpty()){
            throw new RuntimeException("栈为空");
        }
        E target = elemetData[size - 1];
        return target;
    }

    /**
     * 判空
     * @return
     */
    public boolean isEmpty(){
        return size == 0;
    }

    /**
     * 扩容
     */
    private void resize(){
        //计算新数组长度
        int newLength = elemetData.length * 2;
        //创建数组
        E[] newArray = (E[]) new Object[newLength];
        //复制
        System.arraycopy(elemetData,0,newArray,0,size);
        //指向
        elemetData = newArray;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < size; i++) {
            builder.append("[" + (elemetData[i] == null ? "null" : elemetData[i]) + "]");
        }
        return builder.toString();
    }


    public static void main(String[] args) {
        IStack<String> stack = new IStack<>();
//        stack.pop();
        stack.push("2");
        stack.push("3");
        stack.push("4");
        stack.push("4");
        stack.push("4");
        stack.push("6");
        stack.push("7");
        String pop = stack.pop();
        stack.push("5");
        stack.peek();
        boolean empty = stack.isEmpty();

    }

}

posted @ 2020-04-18 15:54  史诗级菜鸟~  阅读(201)  评论(0编辑  收藏  举报