[알고리즘/자료구조] JavaScript 스택(Stack) 구현하기

김효선·2021년 2월 18일
1

알고리즘

목록 보기
2/6

스택(Stack)

  • 스택은 자료구조형에 속한다.
  • 먼저 들어간 자료가 나중에 나오는 후입선출 자료구조로, LIFO(Last In First Out)라고도 부른다.
  • 데이터를 입력하는 push()와 데이터를 제거하는 pop() 등의 작업을 할 수 있다.
  • ctrl+Z로 이전 작업을 취소하는 동작 등에서 사용된다.

자바스크립트 기본 배열 메소드를 사용하지 않고 구현해보기.

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;
  }
}

let stack = new Stack();
stack.push(1); // arr: [1], index: 1
stack.push(2); // arr: [1, 2], index: 2
stack.push(3); // arr: [1, 2, 3], index: 3
console.log(stack.pop()); // 3 , index: 2
console.log(stack.pop()); // 2 , index: 1
console.log(stack.pop()); // 1 , index: 0
console.log(stack.pop()); // null
profile
차근차근 나아가는 주니어 프론트엔드 개발자

0개의 댓글