코딩 테스트 대비 저장용 포스트입니다.
class Stack {
constructor() {
this.stack = [];
this.length = 0;
}
push(value) {
this.stack.push(value);
return ++this.length;
}
pop() {
if (this.length === 0) {
return -1;
}
this.length--;
return this.stack.pop();
}
top() {
if (this.length === 0) {
return -1;
}
return this.stack[this.stack.length - 1];
}
empty() {
return this.length === 0 ? 1 : 0;
}
}
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().split("\n");
const [N, ...orders] = input;
const stk = new Stack();
let answer = "";
orders.forEach((order) => {
if (order.startsWith("push")) {
const [_, value] = order.split(" ");
return stk.push(value);
}
if (order === "top") {
return (answer = answer.concat(`\n${stk.top()}`));
}
if (order === "pop") {
return (answer = answer.concat(`\n${stk.pop()}`));
}
if (order === "size") {
return (answer = answer.concat(`\n${stk.length}`));
}
if (order === "empty") {
return (answer = answer.concat(`\n${stk.empty()}`));
}
});
console.log(answer.trim());