--- comments: true --- # 5.2 Queue A queue is a linear data structure that follows the First-In-First-Out (FIFO) rule. As the name suggests, a queue simulates the phenomenon of lining up, where newcomers join the queue at the rear, and the person at the front leaves the queue first. As shown in Figure 5-4, we call the front of the queue the "head" and the back the "tail." The operation of adding elements to the rear of the queue is termed "enqueue," and the operation of removing elements from the front is termed "dequeue." { class="animation-figure" }
Figure 5-4 Queue's first-in-first-out rule
## 5.2.1 Common operations on queue The common operations on a queue are shown in Table 5-2. Note that method names may vary across different programming languages. Here, we use the same naming convention as that used for stacks.Table 5-2 Efficiency of queue operations
Figure 5-5 Implementing Queue with Linked List for Enqueue and Dequeue Operations
Below is the code for implementing a queue using a linked list: === "Python" ```python title="linkedlist_queue.py" class LinkedListQueue: """Queue class based on linked list""" def __init__(self): """Constructor""" self._front: ListNode | None = None # Head node front self._rear: ListNode | None = None # Tail node rear self._size: int = 0 def size(self) -> int: """Get the length of the queue""" return self._size def is_empty(self) -> bool: """Determine if the queue is empty""" return self._size == 0 def push(self, num: int): """Enqueue""" # Add num behind the tail node node = ListNode(num) # If the queue is empty, make the head and tail nodes both point to that node if self._front is None: self._front = node self._rear = node # If the queue is not empty, add that node behind the tail node else: self._rear.next = node self._rear = node self._size += 1 def pop(self) -> int: """Dequeue""" num = self.peek() # Remove head node self._front = self._front.next self._size -= 1 return num def peek(self) -> int: """Access front element""" if self.is_empty(): raise IndexError("Queue is empty") return self._front.val def to_list(self) -> list[int]: """Convert to a list for printing""" queue = [] temp = self._front while temp: queue.append(temp.val) temp = temp.next return queue ``` === "C++" ```cpp title="linkedlist_queue.cpp" [class]{LinkedListQueue}-[func]{} ``` === "Java" ```java title="linkedlist_queue.java" /* Queue class based on linked list */ class LinkedListQueue { private ListNode front, rear; // Front node front, back node rear private int queSize = 0; public LinkedListQueue() { front = null; rear = null; } /* Get the length of the queue */ public int size() { return queSize; } /* Determine if the queue is empty */ public boolean isEmpty() { return size() == 0; } /* Enqueue */ public void push(int num) { // Add num behind the tail node ListNode node = new ListNode(num); // If the queue is empty, make the head and tail nodes both point to that node if (front == null) { front = node; rear = node; // If the queue is not empty, add that node behind the tail node } else { rear.next = node; rear = node; } queSize++; } /* Dequeue */ public int pop() { int num = peek(); // Remove head node front = front.next; queSize--; return num; } /* Access front element */ public int peek() { if (isEmpty()) throw new IndexOutOfBoundsException(); return front.val; } /* Convert the linked list to Array and return */ public int[] toArray() { ListNode node = front; int[] res = new int[size()]; for (int i = 0; i < res.length; i++) { res[i] = node.val; node = node.next; } return res; } } ``` === "C#" ```csharp title="linkedlist_queue.cs" [class]{LinkedListQueue}-[func]{} ``` === "Go" ```go title="linkedlist_queue.go" [class]{linkedListQueue}-[func]{} ``` === "Swift" ```swift title="linkedlist_queue.swift" [class]{LinkedListQueue}-[func]{} ``` === "JS" ```javascript title="linkedlist_queue.js" [class]{LinkedListQueue}-[func]{} ``` === "TS" ```typescript title="linkedlist_queue.ts" [class]{LinkedListQueue}-[func]{} ``` === "Dart" ```dart title="linkedlist_queue.dart" [class]{LinkedListQueue}-[func]{} ``` === "Rust" ```rust title="linkedlist_queue.rs" [class]{LinkedListQueue}-[func]{} ``` === "C" ```c title="linkedlist_queue.c" [class]{LinkedListQueue}-[func]{} ``` === "Kotlin" ```kotlin title="linkedlist_queue.kt" [class]{LinkedListQueue}-[func]{} ``` === "Ruby" ```ruby title="linkedlist_queue.rb" [class]{LinkedListQueue}-[func]{} ``` === "Zig" ```zig title="linkedlist_queue.zig" [class]{LinkedListQueue}-[func]{} ``` ### 2. Implementation based on an array Deleting the first element in an array has a time complexity of $O(n)$, which would make the dequeue operation inefficient. However, this problem can be cleverly avoided as follows. We use a variable `front` to indicate the index of the front element and maintain a variable `size` to record the queue's length. Define `rear = front + size`, which points to the position immediately following the tail element. With this design, **the effective interval of elements in the array is `[front, rear - 1]`**. The implementation methods for various operations are shown in Figure 5-6. - Enqueue operation: Assign the input element to the `rear` index and increase `size` by 1. - Dequeue operation: Simply increase `front` by 1 and decrease `size` by 1. Both enqueue and dequeue operations only require a single operation, each with a time complexity of $O(1)$. === "ArrayQueue" { class="animation-figure" } === "push()" { class="animation-figure" } === "pop()" { class="animation-figure" }Figure 5-6 Implementing Queue with Array for Enqueue and Dequeue Operations
You might notice a problem: as enqueue and dequeue operations are continuously performed, both `front` and `rear` move to the right and **will eventually reach the end of the array and can't move further**. To resolve this, we can treat the array as a "circular array" where connecting the end of the array back to its beginning. In a circular array, `front` or `rear` needs to loop back to the start of the array upon reaching the end. This cyclical pattern can be achieved with a "modulo operation" as shown in the code below: === "Python" ```python title="array_queue.py" class ArrayQueue: """Queue class based on circular array""" def __init__(self, size: int): """Constructor""" self._nums: list[int] = [0] * size # Array for storing queue elements self._front: int = 0 # Front pointer, pointing to the front element self._size: int = 0 # Queue length def capacity(self) -> int: """Get the capacity of the queue""" return len(self._nums) def size(self) -> int: """Get the length of the queue""" return self._size def is_empty(self) -> bool: """Determine if the queue is empty""" return self._size == 0 def push(self, num: int): """Enqueue""" if self._size == self.capacity(): raise IndexError("Queue is full") # Calculate rear pointer, pointing to rear index + 1 # Use modulo operation to wrap the rear pointer from the end of the array back to the start rear: int = (self._front + self._size) % self.capacity() # Add num to the rear self._nums[rear] = num self._size += 1 def pop(self) -> int: """Dequeue""" num: int = self.peek() # Move front pointer one position backward, returning to the head of the array if it exceeds the tail self._front = (self._front + 1) % self.capacity() self._size -= 1 return num def peek(self) -> int: """Access front element""" if self.is_empty(): raise IndexError("Queue is empty") return self._nums[self._front] def to_list(self) -> list[int]: """Return array for printing""" res = [0] * self.size() j: int = self._front for i in range(self.size()): res[i] = self._nums[(j % self.capacity())] j += 1 return res ``` === "C++" ```cpp title="array_queue.cpp" [class]{ArrayQueue}-[func]{} ``` === "Java" ```java title="array_queue.java" /* Queue class based on circular array */ class ArrayQueue { private int[] nums; // Array for storing queue elements private int front; // Front pointer, pointing to the front element private int queSize; // Queue length public ArrayQueue(int capacity) { nums = new int[capacity]; front = queSize = 0; } /* Get the capacity of the queue */ public int capacity() { return nums.length; } /* Get the length of the queue */ public int size() { return queSize; } /* Determine if the queue is empty */ public boolean isEmpty() { return queSize == 0; } /* Enqueue */ public void push(int num) { if (queSize == capacity()) { System.out.println("Queue is full"); return; } // Calculate rear pointer, pointing to rear index + 1 // Use modulo operation to wrap the rear pointer from the end of the array back to the start int rear = (front + queSize) % capacity(); // Add num to the rear nums[rear] = num; queSize++; } /* Dequeue */ public int pop() { int num = peek(); // Move front pointer one position backward, returning to the head of the array if it exceeds the tail front = (front + 1) % capacity(); queSize--; return num; } /* Access front element */ public int peek() { if (isEmpty()) throw new IndexOutOfBoundsException(); return nums[front]; } /* Return array */ public int[] toArray() { // Only convert elements within valid length range int[] res = new int[queSize]; for (int i = 0, j = front; i < queSize; i++, j++) { res[i] = nums[j % capacity()]; } return res; } } ``` === "C#" ```csharp title="array_queue.cs" [class]{ArrayQueue}-[func]{} ``` === "Go" ```go title="array_queue.go" [class]{arrayQueue}-[func]{} ``` === "Swift" ```swift title="array_queue.swift" [class]{ArrayQueue}-[func]{} ``` === "JS" ```javascript title="array_queue.js" [class]{ArrayQueue}-[func]{} ``` === "TS" ```typescript title="array_queue.ts" [class]{ArrayQueue}-[func]{} ``` === "Dart" ```dart title="array_queue.dart" [class]{ArrayQueue}-[func]{} ``` === "Rust" ```rust title="array_queue.rs" [class]{ArrayQueue}-[func]{} ``` === "C" ```c title="array_queue.c" [class]{ArrayQueue}-[func]{} ``` === "Kotlin" ```kotlin title="array_queue.kt" [class]{ArrayQueue}-[func]{} ``` === "Ruby" ```ruby title="array_queue.rb" [class]{ArrayQueue}-[func]{} ``` === "Zig" ```zig title="array_queue.zig" [class]{ArrayQueue}-[func]{} ``` The above implementation of the queue still has its limitations: its length is fixed. However, this issue is not difficult to resolve. We can replace the array with a dynamic array that can expand itself if needed. Interested readers can try to implement this themselves. The comparison of the two implementations is consistent with that of the stack and is not repeated here. ## 5.2.3 Typical applications of queue - **Amazon orders**: After shoppers place orders, these orders join a queue, and the system processes them in order. During events like Singles' Day, a massive number of orders are generated in a short time, making high concurrency a key challenge for engineers. - **Various to-do lists**: Any scenario requiring a "first-come, first-served" functionality, such as a printer's task queue or a restaurant's food delivery queue, can effectively maintain the order of processing with a queue.