seunghyun Note

[백준] 28278번 : 스택 2 (스택 공부 부수기) with JS 본문

코딩테스트/프로그래머스

[백준] 28278번 : 스택 2 (스택 공부 부수기) with JS

승숭슝현 2024. 1. 18. 14:38

링크 : https://www.acmicpc.net/problem/28278

 

28278번: 스택 2

첫째 줄에 명령의 수 N이 주어진다. (1 ≤ N ≤ 1,000,000) 둘째 줄부터 N개 줄에 명령이 하나씩 주어진다. 출력을 요구하는 명령은 하나 이상 주어진다.

www.acmicpc.net

 

문제 풀이

1 X: 정수 X를 스택에 넣는다. (1 ≤ X ≤ 100,000) stack.push()
2: 스택에 정수가 있다면 맨 위의 정수를 빼고 출력한다. 없다면 -1을 대신 출력한다. stack.pop()
3: 스택에 들어있는 정수의 개수를 출력한다. stack.length
4: 스택이 비어있으면 1, 아니면 0을 출력한다. stack의 empty여부 확인
5: 스택에 정수가 있다면 맨 위의 정수를 출력한다. 없다면 -1을 대신 출력한다. stack[stack.length-1]

const fs = require("fs");

//const input = require("fs").readFileSync("/dev/stdin").toString().split("\n");
const input = fs.readFileSync("예제.txt").toString().trim().split("\n");
const [n, ...arr] = input;
const stack = [];
const result = [];
for (let i = 0; i < arr.length; i++) {
  let query = arr[i];
  const [cmd, value] = query.split(" ");
  switch (cmd) {
    case "1":
      stack.push(parseInt(value));
      break;
    case "2":
      if (stack.length > 0) result.push(stack.pop());
      else result.push(-1);
      break;
    case "3":
      result.push(stack.length);
      break;
    case "4":
      result.push(stack.length === 0 ? 1 : 0);
      break;
    case "5":
      if (stack.length > 0) {
        result.push(stack[stack.length - 1]);
      } else {
        result.push(-1);
      }
      break;
    default:
      break;
  }
}

console.log(result.join("\n"));
728x90