栈 01 基于动态数组的栈

栈接口的定义

  • 定义栈的接口,具体的实现可以使用不同的底层数据结构;
public interface Stack {

    int getSize();
    boolean isEmpty();
    void push(E e);
    E pop();
    E peek();

}

基于动态数组实现的栈

  • ArrayStack 底层使用了动态数组实现了数据结构栈;
package _03.stack._02;

public class ArrayStack implements Stack{

    private Array array;

    public ArrayStack(int capacity){
        array = new Array<>(capacity);
    }

    public ArrayStack(){
        array = new Array<>();
    }

    @Override
    public int getSize(){
        return array.getSize();
    }

    @Override
    public boolean isEmpty(){
        return array.isEmpty();
    }

    public int getCapacity(){
        return array.getCapacity();
    }

    @Override
    public void push(E e){
        array.addLast(e);
    }

    @Override
    public E pop(){
        return array.removeLast();
    }

    @Override
    public E peek(){
        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();
    }

}

测试

public class Main {

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack<>();

        for(int i = 0 ; i < 5 ; i ++){
            stack.push(i);
            System.out.println(stack);
        }

        stack.pop();
        System.out.println(stack);
    }

}
输出:

Stack: [0] top
Stack: [0, 1] top
Stack: [0, 1, 2] top
Stack: [0, 1, 2, 3] top
Stack: [0, 1, 2, 3, 4] top
Stack: [0, 1, 2, 3] top

你可能感兴趣的:(栈 01 基于动态数组的栈)