Algorithm

[Algorithm] Stack

Donghwan 2021. 9. 21. 17:44

import java.util.ArrayList;
import java.util.function.Function;

public class Stack<T> {
    private ArrayList<T> items = new ArrayList<>();

    public Stack() {
        itemsNullCheck();
    }

    public T peek() {
        return getTop(this::peekLogic);
    }

    public T pop() {
        return getTop(this::popLogic);
    }

    public void push(T item) {
        this.items.add(item);
    }

    public int size() {
        return this.items.size();
    }

    public boolean empty() {
        return (this.items.size() == 0) ? true : false;
    }

    private void itemsNullCheck() {
        if (this.items == null) throw new NullPointerException();
    }

    private T getTop(Function<Integer, T> function) {
        if (items.size() > 0) {
            int lastIndex = items.size() - 1;
            return function.apply(lastIndex);
        } else {
            throw new IndexOutOfBoundsException();
        }
    }

    private T popLogic(int lastIndex) {
        int index = items.size() - 1;
        T result = items.get(index);
        items.remove(result);
        return result;
    }

    private T peekLogic(int lastIndex) {
        return items.get(lastIndex);
    }
}
728x90
반응형