글 목록으로
자료구조 큐 이론
#이론#자료구조#큐
큐의 FIFO 구조와 front·rear를 이용한 삽입·삭제 방식을 살펴보고, JavaScript에서 클래스로 큐를 구현하는 방법과 배열 사용 시의 시간 복잡도를 정리합니다.
큐란?
: FIFO(First In First Out)의 형태를 가진, 먼저 들어온 데이터가 가장 먼저 나가는 구조이다.
=> 편의점에서 유통기한별로 제품을 출고하는 경우
- 먼저 들어간 자료가 가장 먼저 나오는 FIFO 구조
- 큐의 한쪽 끝은 프론트(front)로 정하여 삭제 연산만 수행
- 다른 한쪽 끝은 리어(rear)로 정하여 삽입 연산만 수행
- 그래프의 너비 우선 탐색(BFS)에 사용
- 컴퓨터 버퍼에서 주로 사용

- 큐는 front와 rear의 위치로 데이터의 삽입과 삭제를 처리하므로 시간 복잡도는 O(1)이다.
JS에서의 사용 형태
: JS에서는 큐가 따로 없기에 class로 만들어 줘야 한다.
클래스로 만든 큐
class Queue {
constructor() {
this.storage = new Object();
this.front = 0;
this.rear = 0;
}
size() {
return this.rear - this.front;
}
enqueue(element) {
this.storage[this.rear] = element;
this.rear++;
}
dequeue() {
let removed = this.storage[this.front];
delete this.storage[this.front];
this.front++;
if (this.front === this.rear) {
this.front = 0;
this.rear = 0;
}
return removed;
}
}
let queue = new Queue();
queue.enqueue("Dog");
queue.enqueue("Cat");
queue.enqueue("Pig");
queue.enqueue("Cow");
queue.dequeue(); // Dog
queue.dequeue(); // Cat
console.log(queue); // { storage: { '2': 'Pig', '3': 'Cow' }, front: 2, rear: 4 }
console.log(queue.size()); // 2
Array를 큐처럼 사용
: Array로도 큐처럼 사용할 수 있지만, 시간 복잡도가 O(N)을 가지게 된다.
// dequeue로 사용
array.shift();
// enqueue로 사용
array.push();
참고