특징

장점과 단점

예시 코드

class CircularQueue {
    constructor(size) {
        this.elements = Array(size);
        this.size = size;
        this.front = 0;
        this.rear = 0;
        this.currentLength = 0;
    }

    isEmpty() {
        return this.currentLength === 0;
    }

    enqueue(item) {
        if (this.currentLength === this.size) throw new Error('Full!');
        // 데이터를 rear에 넣고, rear는 다음 위치로 이동, 끝에 도달하면 0으로
        this.elements[this.rear] = item;
        this.rear = (this.rear + 1) % this.size;
        this.currentLength++;
    }

    dequeue() {
        if (this.isEmpty()) throw new Error('Empty!');
        // front 위치의 데이터를 삭제, front를 다음 위치로 이동, 끝에 도달하면 0으로
        const item = this.elements[this.front];
        this.front = (this.front + 1) % this.size;
        this.currentLength--;
        return item;
    }

    peek() {
        if (this.isEmpty()) return null;
        return this.elements[this.front];
    }
}

const queue = new CircularQueue(4);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
console.log(queue.peek());
queue.dequeue();
console.log(queue.peek());