
First In , First Out
//pop, push, peek, isEmpty
class Stack<T> {
class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
private Node<T> top; //맨 위에 있는 값의 주소만 기억하면 된다.
//가장 위의 값 제거
public T pop() {
if (top == null) {
throw new EmptyStackException();
}
T item = top.data;
top = top.next;
return item;
}
//가장 위로 값 추가
public void push(T item) {
Node<T> t = new Node<>(item);
t.next = top; //
top = t;
}
//가장 위 값 return
public T peek() {
if (top == null) {
throw new EmptyStackException();
}
return top.data;
}
//stack이 비었는지 확인
public boolean isEmpty() {
return top == null;
}
}
//확인해보기
public class Test {
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
System.out.println(s.pop());
}
}

peek()은 stack에서 제거하는 게 아니기 때문에 남아있는 걸 볼 수 있다.
'개발 > 알고리즘&자료구조' 카테고리의 다른 글
| [자료구조] Queue Java로 구현하기 (0) | 2022.02.08 |
|---|