Algorithm/BOJ
[알고리즘/백준/10828] 스택(자료구조)
개발자 김비숑
2023. 5. 24. 08:12
반응형
문제
https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
풀이
class Stack {
constructor() {
this.stack = [];
}
push(newElement) {
this.stack.push(newElement);
}
pop() {
if (this.empty()) return -1;
return this.stack.pop();
}
size() {
return this.stack.length;
}
empty() {
return this.stack.length === 0 ? 1 : 0;
}
top() {
if (this.empty()) return -1;
return this.stack.at(-1);
}
}
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const [n, ...arr] = fs.readFileSync(filePath).toString().trim().split("\n");
const commands = arr.map((command) => command.split(" "));
const stack = new Stack();
let answer = [];
for (let [com, num] of commands) {
if (com === "push") {
stack.push(num);
} else {
answer.push(stack[com]());
}
}
console.log(answer.join("\n"));
반응형