JavaScript Queue

post-thumbnail

Queue

  • FIFO(First In First Out), 선입선출
  • 한쪽으로 데이터를 삽입하고 한쪽으로 삭제함

자바스크립트 기본배열로도 queue의 구현이 가능하지만, shift 메서드가 왼쪽껄 꺼내서 다시 재정렬하는 방식이라 매우 비효율적인 것으로 알고 있음.
노드를 이용해서 구현하는 방식을 알아두면 매우 쓸모있을 것 같아 정리한다.

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

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

  enqueue(value) {
    this.length++;
    if (this.length === 1) {
      this.head = this.tail = new Node(value);
      return;
    }

    const newNode = new Node(value);
    this.tail.next = newNode;
    this.tail = newNode;
  }

  dequeue() {
    this.length--;
    const value = this.head.value;

    if (this.length === 0) {
      this.head = this.tail = null;
      return value;
    }

    this.head = this.head.next;
    return value;
  }
}

2개의 댓글

comment-user-thumbnail
2022년 9월 5일

굳~~!!

1개의 답글