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
반응형
'Algorithm' 카테고리의 다른 글
[Algorithm] 삽입정렬 (0) | 2021.11.26 |
---|---|
[Algorithm] 선택정렬 (0) | 2021.11.26 |
[Algorithm] Vector (0) | 2021.10.06 |
[Algorithm] BOJ 1158 (0) | 2021.07.28 |
[Algorithm] BOJ 1260 (0) | 2021.07.28 |
댓글