Chapter 8 · Simulation

Circular Queue Simulator

← Chapter 8

Ring view

Array view

Step

Choose an operation.

Code

    Circular Queue Simulator

    An array-based queue that treats its array as a ring. Two numbers describe the whole queue: front, the index of the first item, and size, the number of items. The next free slot is not stored but computed: avail = (front + size) % data.length.

    How to use it

    • Enqueue, Dequeue and Peek run enqueue(item), dequeue() and first(). At each step the current Java line is highlighted and the index arithmetic is shown.
    • Capacity N starts an empty queue of that size. When the queue is full chooses between throwing a "full" exception and doubling the array with resize(2 · N).
    • Wraparound Example loads N = 5, front = 2, size = 2 (30, 40): enqueue(50) writes to data[4], and the next two writes wrap around to data[0] and data[1].
    • Cancel stops the running operation and restores the queue to its state before it.

    Reading the views

    • Ring view: each sector is one array slot. The red outline marks front; the orange sector is the slot being read or written.
    • Array view: the same slots in index order, with ▲front and ▲avail markers. While the array grows, the new array temp appears below.

    Notes

    • A full queue and an empty queue both have front == avail; only size tells them apart.
    • dequeue() writes null into the freed slot so the garbage collector can reclaim the object. No item is ever shifted.
    • Growing copies the items in queue order (temp[k] = data[(front + k) % N]) and sets front = 0. A plain Arrays.copyOf would keep the wrapped order and break the queue.

    Complexity

    OperationTime
    enqueue (no resize), dequeue, firstO(1)
    enqueue with resizeO(n) once, amortized O(1)