push(item): 데이터 삽입pop(): 데이터 삭제 및 반환peek(): 최상단(top)의 데이터 확인 (삭제 X)isEmpty(): 비어있는지 확인enqueue(item): 데이터 삽입 (뒤에서)dequeue(): 데이터 삭제 및 반환 (앞에서)peek(): front 데이터 확인isEmpty(): 비어있는지 확인구분 Stack (스택) Queue (큐)
구조 LIFO (후입선출) FIFO (선입선출)
삽입 위치 Top (맨 위) Rear (뒤)
삭제 위치 Top (맨 위) Front (앞)
시간 복잡도 O(1) O(1)
주요 응용 재귀, 되돌리기, DFS 대기열, BFS, 스케줄링
class Stack {
private List<Integer> list = new ArrayList<>();
public void push(int value) {
list.add(value);
}
public int pop() {
if (list.isEmpty()) throw new RuntimeException("Stack is empty");
return list.remove(list.size() - 1);
}
public int peek() {
if (list.isEmpty()) throw new RuntimeException("Stack is empty");
return list.get(list.size() - 1);
}
public boolean isEmpty() {
return list.isEmpty();
}
}
class Queue {
private LinkedList<Integer> list = new LinkedList<>();
public void enqueue(int value) {
list.addLast(value);
}
public int dequeue() {
if (list.isEmpty()) throw new RuntimeException("Queue is empty");
return list.removeFirst();
}
public int peek() {
if (list.isEmpty()) throw new RuntimeException("Queue is empty");
return list.getFirst();
}
public boolean isEmpty() {
return list.isEmpty();
}
}