java数据结构之动态数组实现栈

接口

public interface Stack <E>{
    int getSize();
    boolean isEmpty();
    void push(E e);
    E pop();
    E peek();
}

public class ArrayStack<E> implements Stack<E> {
    Array<E> array;
/***************构造函数**************/
    public ArrayStack(int Capacity){
        array = new Array<>(Capacity);
    }
    public ArrayStack(){
        this(0);
    }
//获得栈大小
    public int getSize(){
        return array.getSize();
    }
    //判断栈是否为空
    public boolean isEmpty(){
        return array.isEmpty();
    }
    //获得栈容积
    public int getCapacity(){
        return array.getCapacity();
    }
    //入栈
    public void push(E e){
        array.addLast(e);
    }
    //出栈
    public E pop(){
        return array.removeLast(e);
    }
    //查看栈顶top元素
    public E peek(E){
        return array.getLast()
    }

     @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Stack:");
        res.append('[');
        for (int i = 0; i <array.getSize() ; i++) {
            res.append(array.get(i));
            if (i!=array.getSize()-1){
                res.append(", ");
            }
        }
        res.append("] top");
        return res.toString();
    }
}

时间复杂度


int getSize();//O(1)
boolean isEmpty();//O(1)
void push(E e);//均摊O(1)
E pop();//均摊O(1)
E peek();//O(1)

猜你喜欢

转载自blog.csdn.net/weixin_41263632/article/details/81736582