알고리즘
[백준 10826번] 스택 - JavaScript
미누라니까요
2025. 1. 31. 17:49
728x90
반응형
SMALL
이 문제는 한줄씩 오는 명령을 보고 스택의 각 기능을 수행하는 문제이다.
다른 언어로 진행했다면 스택도 구현해야 했겠지만 JavaScript는 기본적으로 스택의 push, pop을 지원하기 때문에 손쉽게 코드를 작성할 수 있었다.
forEach를 사용하여 한줄씩 명령을 수행하도록 하였고, undefined가 출력되지 않도록 출력 배열 또한 만들어 수행하였다.
소스 코드
const input = require('fs')
.readFileSync('/dev/stdin')
.toString()
.trim()
.split('\n');
const num = +input.shift();
const stack = [];
const result = [];
input.forEach((sentence) => {
const [command, value] = sentence.split(' ');
if (command === 'push') {
stack.push(Number(value));
} else if (command === 'pop') {
result.push(stack.length === 0 ? -1 : stack.pop());
} else if (command === 'size') {
result.push(stack.length);
} else if (command === 'empty') {
result.push(stack.length === 0 ? 1 : 0);
} else if (command === 'top') {
result.push(stack.length === 0 ? -1 : stack[stack.length - 1]);
}
});
console.log(result.join('\n'));
728x90
반응형
LIST