자료구조 Queue를 구현해서 해결할 수 있는 문제.
JS는 언어적으로 Queue를 지원하지 않아서 Queue Class를 선언해서 풀었다.
문제에서 주어지는 N이 200만으로 작기 때문에 JS의 배열을 Queue로 생각하고 구현해도 되지만 이전에 코테풀 때 Array의 shift 함수를 남발하여 시간초과가 난 기억이 있어서 링크드리스트로 구현했다.
c++은 queue 자료구조를 지원해서 쉽게 풀었다.
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const N = Number(input[0]);
const commands = input.slice(1);
class Node {
prev = null;
next = null;
constructor(value) {
this.value = value;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(value) {
const newNode = new Node(value);
if (!this.head) this.head = newNode;
if (this.tail) {
this.tail.next = newNode;
newNode.prev = this.tail;
}
this.tail = newNode;
this.length += 1;
}
pop() {
if (this.length === 0) return -1;
const value = this.head.value;
this.head = this.head.next;
this.length -= 1;
return value;
}
size() {
return this.length;
}
empty() {
return this.length === 0 ? 1 : 0;
}
front() {
return this.length ? this.head.value : -1;
}
back() {
return this.length ? this.tail.value : -1;
}
}
const solution = (N, commands) => {
const queue = new Queue();
let answer = '';
commands.forEach((c) => {
const [command, value] = c.split(' ');
if (command === 'push') queue[command](value);
else answer += queue[command]() + '\n';
});
return answer;
};
console.log(solution(N, commands));
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
queue<int> Q;
int N;
string cmd;
cin >> N;
for (int i=0; i<N; i++) {
cin >> cmd;
if (cmd == "push") {
int val;
cin >> val;
Q.push(val);
} else if (cmd == "pop") {
if (Q.empty()) {
cout << -1 << '\n';
} else {
cout << Q.front() << '\n';
Q.pop();
}
} else if (cmd == "size") {
cout << (int)Q.size() << '\n';
} else if (cmd == "empty") {
cout << Q.empty() << '\n';
} else if (cmd == "front") {
if (Q.empty()) cout << -1 << '\n';
else cout << Q.front() << '\n';
} else if (cmd == "back") {
if (Q.empty()) cout << -1 << '\n';
else cout << Q.back() << '\n';
}
}
return 0;
}