코딩 테스트 대비 저장용 포스트입니다.
"use strict";
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.first = null;
this.last = null;
this.lenght = 0;
}
push(value) {
const node = new Node(value);
if (this.lenght === 0) {
this.first = node;
this.last = node;
} else {
this.last.next = node;
this.last = node;
}
return ++this.lenght;
}
pop() {
if (this.first === null) {
return null;
}
if (this.first === this.last) {
this.last = null;
}
const result = this.first.value;
this.first = this.first.next;
this.lenght--;
return result;
}
}
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().split("\n");
const [N, ...orders] = input;
const q = new Queue();
let answer = "";
orders.forEach((order) => {
if (order.startsWith("push")) {
const [_, value] = order.split(" ");
return q.push(value);
}
if (order === "front") {
return (answer = q.lenght === 0 ? answer.concat("\n-1") : answer.concat(`\n${q.first.value}`));
}
if (order === "back") {
return (answer = q.lenght === 0 ? answer.concat("\n-1") : answer.concat(`\n${q.last.value}`));
}
if (order === "size") {
return (answer = answer.concat(`\n${q.lenght}`));
}
if (order === "empty") {
return (answer = answer.concat(`\n${q.lenght === 0 ? 1 : 0}`));
}
if (order === "pop") {
return (answer = q.lenght === 0 ? answer.concat("\n-1") : answer.concat(`\n${q.pop()}`));
}
});
console.log(answer.slice(1)); // 맨 앞 공백 제거, trim() 써도 괜찮았을 듯..