정현수
현수 세상
정현수
전체 방문자
오늘
어제
반응형
  • 분류 전체보기 (267)
    • NEXTSTEP 자바스크립트 클린코드 2기 (1)
    • 우테코 4기 (6)
    • 회고록 (5)
    • 개발지식 (6)
    • React (3)
      • React Clone Coding (3)
    • React Native (2)
    • Kubernetes & Docker (36)
      • 궁금한 것 (13)
    • Flutter (2)
    • 알고리즘 (168)
      • 프로그래머스 1단계 (27)
      • 프로그래머스 2단계 (37)
      • 백준 (98)
      • 이론 (6)
    • 자료구조 (3)
    • 유튜브 (1)
    • 책 읽자 (1)
    • 취업준비 (1)
    • 대내 활동 (31)
      • 2022년 겨울방학 알고리즘 특강 (0)
      • 2020년 여름방학 모각코 (13)
      • 2020년 겨울방학 모각코 (13)
      • 웹프로그래밍 상상튜터링 (5)

인기 글

최근 글

공지사항

  • 블로그 이동

태그

  • replicaset
  • 레플리카셋
  • 백준
  • kubelet
  • image pull
  • mysql
  • 알고리즘
  • flutter
  • image run
  • Jenkins
  • 노드
  • 자바스크립트
  • 우테코
  • 그리디
  • docker
  • React
  • 프로그래머스
  • 리액트
  • 디플로이먼트
  • programmers
  • javascript
  • 개발지식
  • 파이썬
  • Deployment
  • NodePort
  • Kubernetes
  • 모각코
  • 쿠버네티스
  • 이코테
  • 공식문서

최근 댓글

블로그 메뉴

  • 홈

티스토리

hELLO · Designed By 정상우.
정현수

현수 세상

[자료구조] 자바스크립트로 큐(Queue) 구현하기
자료구조

[자료구조] 자바스크립트로 큐(Queue) 구현하기

2022. 2. 7. 13:16
반응형

큐(Queue)

후입선출

나중에 넣은 아이템을 먼저 뺀다.

 

https://namu.wiki/w/%ED%81%90(%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0)

 

자바스크립트 코드

자바스크립트에서 shift와 push를 이용하고 배열을 이용해서 푸는 방법이 있다.

근데 아래 추천문제에서는 시간 초과가 나기 때문에 자바스크립트는

큐를 직접 구현해서 써야한다...

 

Node와 Queue를 구현해 아래문제를 풀어보았다.

const path = process.platform === "linux" ? "/dev/stdin" : "input.txt"; // 리눅스로 테스트할 땐 따로 설정해주어야 합니다.
const input = require("fs").readFileSync(path).toString().trim().split("\n");

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

class Queue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.size = 0;
  }

  push(item) {
    const node = new Node(item);
    if (!this.tail) {
      this.tail = node;
    } else {
      this.head.next = node;
    }
    this.head = node;
    this.size += 1;
  }

  pop() {
    if (!this.getSize()) {
      return -1;
    } else {
      const poped = this.tail.item;
      this.tail = this.tail.next;
      this.size -= 1;
      return poped;
    }
  }

  getSize() {
    return this.size;
  }

  front() {
    return this.getSize() ? this.tail.item : -1;
  }

  back() {
    return this.getSize() ? this.head.item : -1;
  }

  empty() {
    return this.getSize() ? 0 : 1;
  }
}

function solution(input) {
  const queue = new Queue();
  const answer = [];

  for (let i = 1; i < input.length; i += 1) {
    const command = input[i].split(" ")[0];

    switch (command) {
      case "push":
        queue.push(input[i].split(" ")[1]);
        break;
      case "pop":
        answer.push(queue.pop());
        break;
      case "front":
        answer.push(queue.front());
        break;
      case "back":
        answer.push(queue.back());
        break;
      case "size":
        answer.push(queue.getSize());
        break;
      case "empty":
        answer.push(queue.empty());
        break;
    }
  }

  return answer.join("\n");
}

const answer = solution(input);
console.log(answer);

 

추천 문제

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

 

10845번: 큐

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

www.acmicpc.net

 

반응형

'자료구조' 카테고리의 다른 글

[자료구조] 자바스크립트로 스택(Stack) 구현하기  (2) 2022.01.18
[파이썬] 우선순위 큐(Priority Queue), 힙(Heap)  (0) 2021.01.07
    정현수
    정현수
    깃허브 : https://github.com/junghyeonsu 개인 블로그 : https://junghyeonsu.com/ (양질의 글을 올리려고 항상 노력합니다.)

    티스토리툴바