const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\n");
let newInput = input.map((item) => item.split(" "));
let commandNum = newInput.shift();
let stack = [];
let result = [];
for (let i = 0; i < +commandNum[0]; i++) {
if (newInput[i][0] === "push") {
stack.push(newInput[i][1]);
}
if (newInput[i][0] === "pop") {
if (stack[stack.length - 1]) {
result.push(stack.pop());
} else {
result.push(-1);
}
}
if (newInput[i][0] === "size") {
result.push(stack.length);
}
if (newInput[i][0] === "empty") {
if (stack.length === 0) {
result.push(1);
} else {
result.push(0);
}
}
if (newInput[i][0] === "top") {
if (stack[stack.length - 1]) {
result.push(stack[stack.length - 1]);
} else {
result.push(-1);
}
}
}
console.log(result.join("\n"));
풀이
사실 요구사항을 읽고 if else문으로 구현만 해주면된다
문제에 명령이 주어질때마다 한줄씩 출력하라해서 if문마다 console.log를 입력했는데 시간초과가 나와서 result 배열에 하나씩 push를 해준다음에 마지막에 join 메소드를 사용하여 개행문자를 넣어주었더니 해결되었다.