[자료구조] 스택(Stack)

SNXWXH·2024년 8월 22일

Algorithms

목록 보기
4/20
post-thumbnail

스택(Stack)

  • LIFO(Last in, Last out) 원칙으로 만들어진 자료구조

⏱️ 시간복잡도

  • 삽입 : O(1)
  • 제거 : O(1)
  • 탐색 : O(N)
  • 접근 : O(N)

⌨️ 구현하기

stack에 대한 ADT

ADT설명
pushstack에 새 요소 추가
popstack의 맨 위에 있는 요소 삭제
peekstack의 맨 위에 있는 요소 확인

코드

class Stack {
  constructor() {
    this._arr = [];
  }
  push(item) {
    this._arr.push(item);
  }
  pop() {
    return this._arr.pop();
  }
  peek() {
    return this._arr[this._arr.length - 1];
  }
}

const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop(); // 3
stack.peek(); // 2

📍 참고

  • 코딩테스트 합격자 되기 JS 편
profile
세상은 호락호락하지 않다. 괜찮다. 나도 호락호락하지 않으니까.

0개의 댓글