본문 바로가기

자료구조

(자료구조) 분류기준[형태]-[선형구조] Stack(스택)

특징

  • stack은 적체, 쌓는다는 의미 / 아래에서 부터 쌓이기 때문에 빼낼 때 맨 위 부터 나온다.
  • 나중에 들어간 자료가 처음으로 나온다. LIFO/Last In First Out
  • 자바스크립트에서 데이터 추가 push, 제거 pop, 맨 마지막에 집어넣은 데이터 확인 peek 등의 작업을 할 수 있다.
  • 스택은 서로 관계가 있는 여러 작업을 연달아 수행하면서 이전의 작업 내용을 저장해 둘 필요가 있을 때 널리 사용된다.

스택 구현하기

class Stack {
  constructor() {
    this.arr = [];
    this.index = 0;
  }
  
  push(item) {
    this.arr[this.index++] = item;
  }
  
  pop() {
    if (this.index <= 0) return null;
    const result = this.arr[this.index--];
    return result;
  }
  
  peek() {
    return this.arr[this.arr.length - 1]; 
}

let stack = new Stack();
stack.push(1); // arr: [1], index: 1
console.log(stack.pop()); // 3 , index: 2

stack.push(2); // arr: [1, 2], index: 2
console.log(stack.pop()); // 2 , index: 1

stack.push(3); // arr: [1, 2, 3], index: 3
console.log(stack.pop()); // 1 , index: 0

console.log(stack.pop()); // null

'자료구조' 카테고리의 다른 글

(자료구조) [Graph] 인접 행렬 생성하기  (0) 2021.10.19