스택(Stack)은 LIFO(Last In, First Out, 후입선출) 방식으로 동작하는 대표적인 자료구조입니다. 가장 나중에 넣은 데이터가 가장 먼저 나오는 특성 때문에 실행 취소(Undo), 브라우저 방문 기록 관리, 재귀 호출 처리 등 다양한 분야에서 활용됩니다.
아래는 자바스크립트의 클래스(class) 문법을 사용해 작성한 스택 클래스의 전체 구현 예제입니다.
스택 클래스 전체 코드
class Stack {
constructor(maxSize) { // 최대 크기가 지정되지 않으면 기본값 설정
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // 스택 값을 담을 배열 초기화
this.container = [];
}
display() {
console.log(this.container);
}
isEmpty() {
return this.container.length === 0;
}
isFull() {
return this.container.length >= this.maxSize;
}
push(element) { // 스택이 가득 찼는지 확인
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
pop() { // 비어 있는지 확인
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}
peek() {
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
return this.container[this.container.length - 1];
}
clear() {
this.container = [];
}
}주요 메서드 설명
- constructor(maxSize): 생성자입니다. maxSize가 숫자가 아니면 기본값인 10으로 설정하고, 스택 데이터를 저장할 container 배열을 초기화합니다.
- display(): 현재 스택에 들어 있는 모든 요소를 콘솔에 출력합니다.
- isEmpty(): 스택이 비어 있는지 검사하여 참(true) 또는 거짓(false)을 반환합니다.
- isFull(): 스택의 크기가 최대 용량(maxSize)에 도달했는지 확인합니다.
- push(element): 스택이 가득 차 있으면 "Stack Overflow!" 메시지를 출력하고 종료하며, 여유가 있다면 맨 위에 새 요소를 추가합니다.
- pop(): 스택이 비어 있으면 "Stack Underflow!" 메시지를 출력하고, 그렇지 않으면 맨 위 요소를 제거합니다.
- peek(): 요소를 제거하지 않고 스택의 맨 위 값만 확인하여 반환합니다.
- clear(): 스택의 모든 요소를 삭제하여 처음 상태로 초기화합니다.
사용 예시
const stack = new Stack(5); stack.push(10); stack.push(20); stack.push(30); stack.display(); // [10, 20, 30] console.log(stack.peek()); // 30 stack.pop(); stack.display(); // [10, 20] console.log(stack.isEmpty()); // false stack.clear(); console.log(stack.isEmpty()); // true
이처럼 스택 클래스를 직접 구현하면 내부 동작 원리를 이해할 수 있고, 최대 크기 제한과 오버플로·언더플로 처리 같은 실무적인 예외 상황도 함께 다룰 수 있습니다. 자료구조 학습뿐 아니라 코딩 테스트 준비에도 큰 도움이 됩니다.