본문 바로가기
자료구조_알고리즘

자료구조) 자료구조 - Queue

by nomfang 2022. 3. 18.
728x90
반응형

queue

큐는 대기 행렬 이라는 뜻으로
데이터 들이 들어간 순서대로 사용된다
선입 선출(FIFO - First In First Out) 구조

queue의 사용 예

프린터에서 작업 페이지를 순서대로 인쇄하는 것과 같다
queue - 프린터가 작업중이면 queue에 데이터를 순서대로 쌓아둔다
프린터가 작업을 마치면 가장 먼저 들어온 데이터를 프린터로 보냄
프린터 - queue에서 보낸 데이터를 사용

위와 같이 각 프로그램간 존재하는 처리 속도 차이로 인해 데이터가 대기해야할 경우 사용

class를 활용한 queue 구현

class Queue {
  constructor() {
    this.storage = {};
    this.front = 0;
    this.rear = 0;
  }

  size() {
    return this.rear - this.front;
  }

  enqueue(element) {
    this.storage[this.rear] = element;
    this.rear += 1;
  }

  dequeue() {

    if (this.rear === this.front) {
      return;
    }

    const result = this.storage[this.front];
    delete this.storage[this.front];
    this.front += 1;

    return result;
  }
}

배열(array)을 queue로 사용하기

// const array = new Array() 미리 정의된 Array 객체를 사용합니다.
const queue = []; 

queue.push(1); // [1]
queue.push(2); // [1, 2]
queue.push(3); // [1, 2, 3]
queue.push(4); // [1, 2, 3, 4]
queue.push(5); // [1, 2, 3, 4, 5]

console.log(queue); // [1, 2, 3, 4, 5]

queue.shift(); // [2, 3, 4, 5]
queue.shift(); // [3, 4, 5]

console.log(queue); // [3, 4, 5]
반응형

댓글