본문 바로가기
Algorithm/백준[BOJ]

[JS] 백준 18258번 큐2

by jgo 2022. 6. 14.

문제 링크

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

풀이 전략

정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

큐를 이해하고 이를 구현하는 문제이다. 큐의 동작원리를 완전히 이해하고 있어야한다. 

코드 

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class Queue {
    constructor() {
        this.head = null;
        this.rear = null;
        this.length = 0;
    }

    push(data) {
        const node = new Node(data);
        if (!this.head) this.head = node;
        else this.rear.next = node;
        this.rear = node;
        this.length++;
    }

    pop() {
        if (!this.head) return -1;
        const node = this.head.data;
        this.head = this.head.next;
        this.length--;
        return node;
    }

    size() {
        return this.length;
    }

    empty() {
        if (this.size()) return 0;
        else return 1;
    }

    front() {
        if (!this.head) return -1;
        else return this.head.data;
    }

    back() {
        if (!this.head) return -1;
        else return this.rear.data;
    }
}

const n = +input.shift();

solution(input);

function solution(arr) {
    const queue = new Queue();
    let answer = [];
    for (let i = 0; i < n; i++) {
        const [commmand, num] = arr[i].split(" ");

        switch (commmand) {
            case "push":
                queue.push(+num);
                break;
            case "pop":
                answer.push(queue.pop());
                break;
            case "size":
                answer.push(queue.size());
                break;
            case "empty":
                answer.push(queue.empty());
                break;
            case "front":
                answer.push(queue.front());
                break;
            case "back":
                answer.push(queue.back());
                break;
        }
    }
    console.log(answer.join("\n"));
}

 

회고

이전에도 이 코드를 가져다 쓰곤 했지만 완전히 이해하지는 못했었다. 
특히 push의 조건문에 있는 this.rear.next = node;

를 이해하는 것이 어려웠다. 그 밑에 있는

this.rear = node;

이 코드만 있으면 될텐데 왜 굳이 두번쓰는지 이해할 수 없었는데 조건문안의 코드는 다음에 push할 데이터의 자리를 확보하는 것이었다. 이 코드가 없다면 각 노드들끼리 연결되어있지 않아 큐의 기능을 수행할 수 없다. 

 

더 좋은 방법이나 의견이 있으시다면 댓글 부탁드립니다 :)

댓글