Stack
기본적인 자료구조
나중에 넣은 데이터가 먼저 나오는 후입선출 LIFO (Last In First Out)
구조로 데이터를 저장하고 관리하는 자료구조
stack이 쌓다, 쌓아올리다를 의미하듯이 책을 차곡차곡 쌓아올린 상황을 연상하면 이해하기 쉽다. 가장 나중에 쌓은 책을 가장 먼저 꺼낼수 있듯이 자료구조 stack
은 LIFO
구조로 동작한다.
주로 임시 데이터나 함수 호출 등에 사용됩니다.
함수 호출 시에 가장 대표적인 예로는 호출 스택call stack
에 현재 실행 중인 함수의 정보를 저장하여 이전에 호출한 함수로 되돌아갈 때 필요합니다.
웹 브라우저의 방문 기록을 뒤로 가기 버튼으로 이동할 때, 방문 기록을 저장한 스택을 사용합니다.
Top
: 스택의 맨 위에 있는 요소를 가리키는 포인터를 의미합니다.
Bottom
: 스택의 맨 아래에 있는 요소를 가리키는 포인터를 의미합니다.
Overflow
: 스택이 가득 차서 더 이상 요소를 추가할 수 없는 상태를 의미합니다.
Underflow
: 스택이 비어 있어 더 이상 요소를 제거할 수 없는 상태를 의미합니다.
Java
에서의 Stack
import java.util.Stack;
Stack<Integer> stack = new Stack<>();
push(item)
stack
의 가장 위에 있는top
위치에 요소를 추가합니다.Stack<Integer> stack = new Stack<Integer>();
stack.push(10); // 스택에 10 추가
stack.push(20); // 스택에 20 추가
pop()
가장 위에 있는top
데이터를 제거하고 해당 데이터를 반환합니다.
stack
이 비어있을 경우 EmptyStackException
이 발생합니다.
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
int topData = stack.pop(); // 스택에서 데이터 3을 삭제하고 반환합니다.
System.out.println(topData); // 출력 결과: 3
topData = stack.pop(); // 스택에서 데이터 2를 삭제하고 반환합니다.
System.out.println(topData); // 출력 결과: 2
topData = stack.pop(); // 스택에서 데이터 1을 삭제하고 반환합니다.
System.out.println(topData); // 출력 결과: 1
peek()
stack
의 가장 위에 있는top
요소를 반환합니다. 제거하지는 않습니다.
stack
이 비어있을 경우 EmptyStackException
이 발생합니다.
empty()
stack
이 비어있는지 여부를 반환합니다.Stack<Integer> stack = new Stack<>();
// 스택에 요소 추가
stack.push(1);
stack.push(2);
stack.push(3);
// 스택의 맨 위 요소 확인
int topElement = stack.peek();
System.out.println("맨 위의 요소는: " + topElement);
// 스택에 요소가 남아있는지 확인
if (!stack.empty()) {
// 스택에서 요소 제거
int removedElement = stack.pop();
System.out.println("제거된 요소는: " + removedElement);
}
Stack
구현import java.util.ArrayList;
public class MyStack<T> {
private ArrayList<T> stack;
public MyStack() {
stack = new ArrayList<>();
}
public void push(T item) {
stack.add(item);
}
public T pop() {
if (isEmpty()) {
throw new IndexOutOfBoundsException("스택이 비어있습니다.");
}
return stack.remove(stack.size() - 1);
}
public T peek() {
if (isEmpty()) {
throw new IndexOutOfBoundsException("스택이 비어있습니다.");
}
return stack.get(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
public void clear() {
stack.clear();
}
}
MyStack<Integer> stack = new MyStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.peek()); // 3
System.out.println(stack.pop()); // 3
stack.clear();
System.out.println(stack.isEmpty()); // true