자료구조

스택(Stack)

mellomello.made 2022. 6. 19. 18:22

Stack

특징

  • 데이터를 마지막에 밀어 넣고, 마지막에 밀어 넣는 데이터를 먼저 꺼내는 후입 선출(LIFO-Last in First Out)방식의 자료구조.
  • 데이터의 추가와 삭제가 한쪽 방향에서만 일어난다.
  • 스택에 데이터를 밀어 넣는 것을 push라 하고 스택에서 데이터를 꺼내는 것을 pop이라고 한다.
  • pop 메서드와 push 메서드를 사용하면 스택을 쉽게 구현할 수 있다.
  • 스택은 언제나 가장 마지막에 밀어 넣은 최신 데이터를 먼저 취득한다. 

 

스택을 생성자 함수로 구현해 보면 다음과 같다.

 

const Stack = (function () {
  function stack(array = []) {
    if (!Array.isArray(array)) {
      throw new TypeError(`${array} is not an array.`);
    }
    this.array = array;
  }
  stack.prototype = {
    Constructor: Stack,
    //스택의 가장 마지막에 데이터를 밀어 넣는다.
    push(value) {
      return this.array.push(value);
    },
    //스택의 가장 마지막 데이터, 즉 가장 나중에 밀어 넣은 최신 데이터를 꺼낸다.
    pop() {
      return this.array.pop();
    },
    //스택의 복사본 배열을 반환한다.
    entries() {
      return [...this.array];
    },
  };
  return Stack;
})();

const stack = new Stack([1, 2]);
console.log(stack.entries()); // [1,2]

stack.push(3);
console.log(stack.entries()); // [1,2,3]

stack.pop();
console.log(stack.entries()); // [1,2]