문제 요약
[boj] 10828. 스택 (node.js)
- 문제에서 원하는 결과를 출력할 수 있도록 스택을 구현하는 문제
내 풀이
핵심 코드
push(value) {
let node = new Node(value);
if (!this.first) {
this.first = this.last = node;
} else {
let temp = this.first;
this.first = node;
this.first.next = temp;
}
this.size++;
return null;
}
pop() {
if (!this.first) return -1;
let node = this.first;
if (this.first == this.last) {
this.first = null;
} else this.first = this.first.next;
this.size--;
return node.value;
}
- 스택 클래스를 정의해서 풀이했다. push, pop 메서드를 정의해 데이터 삽입과 삭제를 구현했다.
- 큐와 마찬가지로 노드를 활용해서 연결한다. 링크드리스트에서 작동 방식을 LIFO (Last-In-First-Out)이 되도록 수정한 것과 같다.
- 구현할 때, 삽입은 마지막으로 삽입된 노드를 매번 this.first 에 넣어주고, 기존 this.first 는 한 칸 밀리게끔 정의한다. 따라서 삭제할 때도 항상 this.first 를 제거하도록 한다. 스택은 마지막으로 삽입된 노드가 가장 먼저 삭제되는 자료구조이지만, Stach 클래스 내부 작동원리는 이처럼 this.first 에 마지막 노드를 삽입해 동작하도록 하면 원리에도 문제가 없고, 코드도 this.prev 를 노드에 추가적인 속성으로 정의할 필요 없이 구현할 수 있다.
주절주절
- 처음 풀 때는 노드의 생성자에 this.prev, this.next 의 두 가지 속성을 추가해서 삽입과 삭제 시 다음 노드 간 연결과 해제에 문제가 없도록 구현했다. 추후 문제를 푸는 방법이 스택의 구조 자체처럼 First-in-Last-out 을 구현할 필요 없이, 저장할 때부터 뒤집어 저장하면 된다는 걸 배웠다!!
전체 코드
const fs = require("fs");
const filePath = process.platform === "linux" ? "dev/stdin" : "input.txt";
const stdin = fs.readFileSync(filePath).toString().split("\n");
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
push(value) {
let node = new Node(value);
if (!this.first) {
this.first = this.last = node;
} else {
let temp = this.first;
this.first = node;
this.first.next = temp;
}
this.size++;
return null;
}
pop() {
if (!this.first) return -1;
let node = this.first;
if (this.first == this.last) {
this.first = null;
} else this.first = this.first.next;
this.size--;
return node.value;
}
getSize() {
return this.size;
}
isEmpty() {
return this.size == 0 ? 1 : 0;
}
top() {
if (!this.first) return -1;
return this.first.value;
}
}
let cnt = 0;
const input = () => stdin[cnt++];
function getCommand(command, num) {
switch (command) {
case "push":
return stack.push(num);
case "pop":
return stack.pop();
case "size":
return stack.getSize();
case "empty":
return stack.isEmpty();
case "top":
return stack.top();
}
}
const N = Number(input());
const stack = new Stack();
let results = [];
for (let i = 0; i < N; i++) {
let [command, num] = input().split(" ");
results.push(getCommand(command, num));
}
console.log(results.filter((elem) => elem != null).join("\n"));