[백준 알고리즘] Node.js 10845. 큐
2023. 7. 21. 11:47ㆍ코딩연습
1. 문제
https://www.acmicpc.net/problem/10845
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
2. 풀이
- Class 형태로 Queue를 만들어서 해결하였다.
const inputs = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const N = +inputs.shift();
class Queue {
constructor(arr) {
this.array = arr;
};
push(value) {
this.array.push(value);
}
pop(){
let popVal = this.array.shift();
if(!popVal) return -1;
return popVal;
}
size(){
return this.array.length;
}
empty(){
let length = this.size();
if(!length) return 1
return 0;
}
front(){
let length = this.size();
if(!length) return -1
return this.array[0];
}
back(){
let length = this.size();
if(!length) return -1;
return this.array[length-1];
}
}
const queue = new Queue([]);
let result = "";
for(let i = 0; i < inputs.length; i++){
const [text, num] = inputs[i].split(" ");
if(text === 'push'){
queue.push(+num);
} else if(text === 'pop'){
result += `${queue.pop()}\n`;
} else if(text === 'size'){
result += `${queue.size()}\n`;
} else if(text === 'empty') {
result += `${queue.empty()}\n`;
} else if(text === 'front'){
result += `${queue.front()}\n`;
} else if(text === 'back'){
result += `${queue.back()}\n`;
}
}
console.log(result);
3. 정리
- 클래스를 직접 정의해서 해결한 적은 처음이라 많이 낯설었지만 생각보다 쉽게 작성할 수 있었다.
'코딩연습' 카테고리의 다른 글
[백준 알고리즘] Node.js 11403. 경로 찾기 (0) | 2023.07.26 |
---|---|
[백준 알고리즘] Node.js 10866. 덱 (0) | 2023.07.21 |
[백준 알고리즘] Node.js 1003. 피보나치 함수 (0) | 2023.07.18 |
[백준 알고리즘] Node.js 12852. 1로 만들기 2 (0) | 2023.07.04 |
[백준 알고리즘] Node.js 1806. 부분합 (0) | 2023.06.28 |