Deque 자료구조를 사용해서 푸는 문제
JS의 경우 Deque가 없기 때문에 이전에 푼 문제에서 Deque 자료구조를 만들었던 것을 가져와서 풀이했다.
그리고 iterator 프로토콜을 사용해 spread 연산자를 사용해서 마지막 출력을 쉽게 할 수 있도록 generator 함수를 Deque의 멤버함수로 추가해주었다.
풀이 자체는 문제에서 요구한대로 풀면 되고, 2번째 명령에서 기존에 하나 뺀걸 기억해뒀다가 추가하는 방식으로 2번째 카드를 뽑는 것을 처리해주었다.
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const N = Number(input[0]);
const commands = input[1].split(' ').map(Number);
class Node {
prev = null;
next = null;
constructor(value) {
this.value = value;
}
}
class Deque {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push_front(value) {
const newNode = new Node(value);
if (this.empty()) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
}
this.length += 1;
}
push_back(value) {
const newNode = new Node(value);
if (this.empty()) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length += 1;
}
pop_front() {
if (this.empty()) return -1;
const front = this.front();
this.head = this.head.next;
this.length -= 1;
return front;
}
pop_back() {
if (this.empty()) return -1;
const back = this.back();
this.tail = this.tail.prev;
this.length -= 1;
return back;
}
size() {
return this.length;
}
empty() {
return this.length === 0 ? 1 : 0;
}
front() {
if (this.empty()) return -1;
return this.head.value;
}
back() {
if (this.empty()) return -1;
return this.tail.value;
}
*[Symbol.iterator]() {
let tmp = this.head;
while (tmp) {
yield tmp.value;
tmp = tmp.next;
}
}
}
const solution = (N, commands) => {
const deque = new Deque();
let i = 1;
while (commands.length) {
const command = commands.pop();
if (command === 1) {
deque.push_front(i);
} else if (command === 2) {
const tmp = deque.pop_front();
deque.push_front(i);
deque.push_front(tmp);
} else if (command === 3) {
deque.push_back(i);
}
i++;
}
return [...deque].join(' ');
};
console.log(solution(N, commands));
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int N; cin >> N;
deque<int> DQ;
stack<int> S;
for (int i=0; i<N; i++) {
int num;
cin >> num;
S.push(num);
}
int cnt = 1;
while(!S.empty()) {
int command = S.top(); S.pop();
if (command == 1) {
DQ.push_front(cnt);
}
else if (command == 2) {
int tmp = DQ.front();
DQ.pop_front();
DQ.push_front(cnt);
DQ.push_front(tmp);
}
else if (command == 3) {
DQ.push_back(cnt);
}
cnt += 1;
}
for (auto v : DQ) cout << v << " ";
return 0;
}