algorithm/BOJ
[JS & Stack] 10828번: 스택
_JunHo
2023. 7. 19. 11:08
const fs = require('fs');
// const input = fs.readFileSync('./testcase.txt').toString().trim();
const input = fs.readFileSync('/dev/stdin').toString().trim();
const inputs = input.split('\n');
const N = inputs[0];
function initMethodInArrayPrototype() {
if (
Array.prototype.at === undefined ||
typeof Array.prototype.at !== 'function'
) {
Array.prototype.at = (index) => {
if (index >= 0) {
if (index < this.length) return this[index];
else return undefined;
}
else {
const ridx = index * -1;
if (ridx > this.length) return undefined;
return this[this.length - ridx];
}
}
}
}
class Stack {
constructor() {
this.stack = [];
}
push(x) {
this.stack.push(x);
}
pop() {
if (this.stack.length === 0) {
return -1;
} else {
return this.stack.pop();
}
}
size() {
return this.stack.length;
}
empty() {
return this.stack.length ? 0 : 1;
}
top() {
if (this.stack.length) {
return this.stack.at(-1);
} else {
return -1;
}
}
}
initMethodInArrayPrototype();
const stack = new Stack();
let answer = '';
for (let i = 1; i <= N; i++) {
const [req, num] = [...inputs[i].split(' ')];
if (req === 'push') {
stack.push(+num);
}
if (req === 'pop') {
answer += stack.pop() + '\n';
}
if (req === 'size') {
answer += stack.size() + '\n';
}
if (req === 'top') {
answer += stack.top() + '\n';
}
if (req === 'empty') {
answer += stack.empty() + '\n';
}
}
console.log(answer);
https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net