基于ArrayList实现的ArrayStack

sixthelement 2020-01-04

参考接口

public interface myStack<T> {
    void push(T element);
    T peek();
    T pop();
    Integer search(T element);
    Integer size();
    void clear();
    Boolean isEmpty();
}

实现代码

import java.util.ArrayList;

public class MyArrayStack<T> implements myStack<T>{
    private ArrayList<T> core;

    public MyArrayStack() {
        this(10);
    }

    public MyArrayStack(int capacity) {
        core = new ArrayList<>(capacity);
    }

    @Override
    public void push(T element) {
        core.add(element);
    }

    @Override
    public T peek() {
        return core.get(core.size() - 1);
    }

    @Override
    public T pop() {
        return core.remove(core.size() - 1);
    }

    @Override
    public Integer search(T element) {
        return core.lastIndexOf(element);
    }

    @Override
    public Integer size() {
        return core.size();
    }

    @Override
    public void clear() {
        core.clear();
    }

    @Override
    public Boolean isEmpty() {
        return core.isEmpty();
    }

    public static void main(String[] args) {
        MyArrayStack<Integer> stack = new MyArrayStack<>();
        for (int i = 0; i < 10; i ++) {
            stack.push(10 - i);
        }
//        System.out.println(stack.size());
//        System.out.println(stack.peek());
//        stack.pop();
//        System.out.println(stack.peek());
//        for (int i = 0 ; i < stack.size(); i ++) {
//            System.out.println(stack.pop());
//        }

    }
}

相关推荐