먼저 넣은 것을 먼저 꺼내는(First In, First Out) 자료구조. 줄을 서듯 뒤에 넣고(enqueue) 앞에서 꺼낸다(dequeue).
구현할 때 주의
JavaScript 배열로 push + shift를 쓰면 shift가 남은 원소를 모두 앞으로 당겨 O(n)이 된다. 원소가 많다면 연결 리스트(head에서 꺼내고 tail에 넣기)나 시작 인덱스를 따로 들고 있는 방식으로 양쪽 모두 O(1)을 만든다.
class Queue<T> {
private items: Record<number, T> = {}
private head = 0
private tail = 0
enqueue(v: T) { this.items[this.tail++] = v }
dequeue() {
if (this.head === this.tail) return undefined
const v = this.items[this.head]
delete this.items[this.head++]
return v
}
}