https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
📌 작성한 코드
// 10828
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "Beakjoon/Silver/test.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\n");
class Stack {
constructor() {
this.list = [];
this.position = 0;
}
push(num) {
this.list.push(num);
this.position++;
}
pop() {
const temp = this.list.pop();
if (temp === undefined) {
return -1;
} else {
this.position--;
return temp;
}
}
size() {
return this.position;
}
empty() {
return this.position === 0 ? 1 : 0;
}
top() {
if (this.position > 0) {
return this.list[this.position - 1];
} else {
return -1;
}
}
}
const N = Number(input[0]);
const s = new Stack();
const answer = [];
for (let i = 1; i <= N; i++) {
const [command, num] = input[i].split(" ");
if (command === "push") s.push(Number(num));
else if (command === "pop") answer.push(s.pop());
else if (command === "top") answer.push(s.top());
else if (command === "size") answer.push(s.size());
else if (command === "empty") answer.push(s.empty());
else if (command === "top") answer.push(s.top());
}
console.log(answer.join("\n"));
📌 풀이
스택을 구현하라고 하길래 position을 사용해서 최대한 스택의 느낌을 살려서 구현해보았다. (length 사용하면 되어서 필요없긴하지만...)
참고로 바로바로 `console.log()`로 연산의 결과를 출력해버리면 시간 초과가 발생한다. 저장해두었다가 한번에 출력하자.
✅ 성공

'알고리즘 > 백준' 카테고리의 다른 글
| [JavaScript/Stack] 백준 골드 5 : 2493 - 탑 (2) | 2024.01.21 |
|---|---|
| [JavaScript/Stack] 백준 실버 2 : 1874 - 스택 수열 (0) | 2024.01.21 |
| [JavaScript/Queue] 백준 실버 4 : 1158 - 요세푸스 문제 (0) | 2024.01.21 |
| [JavaScript/연결리스트] 백준 실버 2 : 1406 - 에디터 (0) | 2024.01.20 |
| [JavaScript] 백준 실버 2 : 5397 - 키로거 (1) | 2024.01.20 |