Algorithm/BOJ

[알고리즘/백준/10866] 덱(Nodejs, 자료구조)

개발자 김비숑 2023. 6. 15. 23:48
반응형

문제


https://www.acmicpc.net/problem/10866

 

10866번: 덱

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

풀이


class Deque {
  constructor() {
    this.deque = [];
  }
  push_front(newElement) {
    this.deque.unshift(newElement);
  }
  push_back(newElement) {
    this.deque.push(newElement);
  }

  pop_front() {
    if (this.empty()) return -1;
    return this.deque.shift();
  }
  pop_back() {
    if (this.empty()) return -1;
    return this.deque.pop();
  }
  size() {
    return this.deque.length;
  }
  empty() {
    return this.size() === 0 ? 1 : 0;
  }
  front() {
    return this.empty() ? -1 : this.deque[0];
  }
  back() {
    return this.empty() ? -1 : this.deque.at(-1);
  }
}

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let [n, ...input] = fs.readFileSync(filePath).toString().trim().split("\n");
const N = +n;
const commands = input.map((row) => row.split(" "));
const deque = new Deque();
const answer = [];

for (let command of commands) {
  // push
  if (command.length === 2) {
    const [c, n] = command;
    deque[c](n);
  } else {
    answer.push(deque[command]());
  }
}

console.log(answer.join("\n"));

 

반응형