문제
풀이
말 그대로 큐를 구현하면 되는 문제
코드
const input = `15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front`.split('\n').map(v=>v.split(' ')).slice(1);
// const input = require("fs").readFileSync("/dev/stdin").toString().trim().split('\n').map(v=>v.split(' ')).slice(1);
class Node {
constructor(number, prev=null, next=null) {
this.number = number;
this.prev = prev;
this.next = next;
}
}
class Queue{
constructor(head, tail) {
this.head = null;
this.tail = null;
this.length = 0;
}
push(number){
const newNode = new Node(Number(number));
if(this.length===0) {
this.head = newNode;
this.tail = newNode;
}else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
}
pop(){
if(this.length === 0) {
answer += -1 + '\n';
return;
}
const temp = this.head.number;
this.head = this.head.next;
this.length--;
if(this.length===0) {
this.tail = null;
}
answer += temp +'\n';
}
size(){
answer += this.length +'\n';
}
empty(){
answer += (this.length ? 0 : 1) +'\n';
}
front(){
answer += (this.head ? this.head.number : -1) +'\n';
}
back(){
answer += (this.tail ? this.tail.number : -1) +'\n';
}
}
const queue = new Queue();
let answer = '';
for (let i=0; i<input.length;i++){
const [order,number] = input[i];
queue[order](number);
}
console.log(answer);
'Algorithm > 문제' 카테고리의 다른 글
programmers. 게임 맵 최단거리 (0) | 2021.04.12 |
---|---|
programmers. 수식 최대화 (0) | 2021.04.11 |
baekjoon. 괄호 (0) | 2021.03.07 |
baekjoon. 주유소 (0) | 2021.01.29 |
baekjoon. 평범한 배낭 (0) | 2021.01.27 |