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]
반응형
'자료구조_알고리즘' 카테고리의 다른 글
알고리즘) 재귀 - 피보나치 수열 (0) | 2022.03.28 |
---|---|
자료구조/알고리즘) 재귀 (0) | 2022.03.22 |
자료구조) 자료구조 - Stack (0) | 2022.03.18 |
자료구조) 자료구조 (0) | 2022.03.18 |
코딩테스트 연습) [1차] 뉴스 클러스터링 (0) | 2021.06.15 |
댓글