Home 스택 Stack
Post
X

스택 Stack

스택에 대해 알아보자.


스택 Stack

스택은 마지막에 삽입된 항목만을 제거하고 접근할 수 있는 LIFO(Last In First Out) 원리를 따르는 자료구조입니다.

stack


스택의 추상 자료형 ADT

  • push : 맨 마지막에 새로운 요소 삽입
  • pop : 맨 마지막 요소 추출하고 반환
  • peek : 맨 마지막 요소 확인
  • size : 스택의 요소 갯수
  • isEmpty : 스택이 비어있는 지 확인

구현 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Stack {
  constructor() {
    this._arr = [];
  }

  push(item) {
    this._arr.push(item);
  }

  pop() {
    return this._arr.pop();
  }

  peek() {
    return this._stack.length ? this._stack[this._stack.length - 1] : null;
  }

  size() {
    return this._arr.length;
  }

  isEmpty() {
    return this._arr.length == 0;
  }
}

push

스택에 자료를 추가하는 것으로 Javascript의 배열이 기본 지원하는 push 메서드를 사용합니다.

1
2
3
4
5
stack.push(1);
stack.push(2);
stack.push(3);

console.log(stack); // {_arr : [1, 2, 3]}
  • 시간복잡도 : O(1)

pop

스택에서 자료를 추출하는 것으로 Javascript의 배열이 기본 지원하는 pop 메서드를 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
stack.push(1);
stack.push(2);
stack.push(3);

console.log(stack); // {_arr : [1, 2, 3]}

stack.pop(); // 3
stack.pop(); // 2
stack.pop(); // 1

console.log(stack); // {_arr : []}
  • 시간복잡도 : O(1)

peek

스택 자료구조에서 마지막에 추가된 항목을 제거하지않고 확인하는 것을 의미합니다.

1
2
3
stack.push(1);

console.log(stack.peek()); // 1

size

스택 자료구조에서 스택 안에 있는 요소들의 갯수를 반환합니다.

1
2
3
4
5
stack.push(1);
stack.push(2);
stack.push(3);

stack.size(); // 3

isEmpty

스택 자료구조에서 스택 안에 요소가 있는 지 확인합니다.

1
2
3
4
stack.isEmpty(); // true

stack.push(1);
stack.isEmpty(); // false
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.