카테고리 없음

[알고리즘] 스택 javascript

ShinBW 2022. 3. 7. 10:30

https://www.acmicpc.net/problem/10828

스택(Stack)의 개념

한 쪽 끝에서만 자료를 넣고 뺄 수 있는 LIFO(Last In First Out) 형식의 자료 구조

스택(Stack)의 연산

스택(Stack)는 LIFO(Last In First Out) 를 따른다. 즉, 가장 최근에 스택에 추가한 항목이 가장 먼저 제거될 항목이다.

  • pop(): 스택에서 가장 위에 있는 항목을 제거한다.
  • push(item): item 하나를 스택의 가장 윗 부분에 추가한다.
  • peek(): 스택의 가장 위에 있는 항목을 반환한다.
  • isEmpty(): 스택이 비어 있을 때에 true를 반환한다.
    출저 - https://gmlwjd9405.github.io/2018/08/03/data-structure-stack.html
  • [[자료구조] 스택(Stack)이란 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io](https://gmlwjd9405.github.io/2018/08/03/data-structure-stack.html)

문제풀이

const array = require('fs').readFileSync('/dev/stdin').toString().split('\n');

const stack = [];
const result = [];

const len = array.shift(); // 맨 처음 녀석을 제거하고 반환 (입출력예시의 맨위값)

for (let i = 0; i < len; i++) {        
    switch(array[i]) {
        case 'pop': 
          result.push(stack.pop() || -1);
          break;

        case 'size': 
          result.push(stack.length);
          break;

        case 'empty': 
          result.push(stack[0] ? 0 : 1);
          break;

        case 'top': 
          result.push(stack[stack.length - 1] || -1);
          break;

        default: 
          stack.push(array[i].split(" ")[1]);
          break;
    }
}

console.log(result.join('\n')); // 한번에 출력되게 조인과 \n 사용