--- comments: true --- # 5.3 Double-ended queue In a queue, we can only delete elements from the head or add elements to the tail. As shown in the following diagram, a double-ended queue (deque) offers more flexibility, allowing the addition or removal of elements at both the head and the tail. { class="animation-figure" }
Figure 5-7 Operations in double-ended queue
## 5.3.1 Common operations in double-ended queue The common operations in a double-ended queue are listed below, and the names of specific methods depend on the programming language used.Table 5-3 Efficiency of double-ended queue operations
Figure 5-8 Implementing Double-Ended Queue with Doubly Linked List for Enqueue and Dequeue Operations
The implementation code is as follows: === "Python" ```python title="linkedlist_deque.py" class ListNode: """Double-linked list node""" def __init__(self, val: int): """Constructor""" self.val: int = val self.next: ListNode | None = None # Reference to the next node self.prev: ListNode | None = None # Reference to predecessor node class LinkedListDeque: """Double-ended queue class based on double-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 # Length of the double-ended queue def size(self) -> int: """Get the length of the double-ended queue""" return self._size def is_empty(self) -> bool: """Determine if the double-ended queue is empty""" return self._size == 0 def push(self, num: int, is_front: bool): """Enqueue operation""" node = ListNode(num) # If the list is empty, make front and rear both point to node if self.is_empty(): self._front = self._rear = node # Front enqueue operation elif is_front: # Add node to the head of the list self._front.prev = node node.next = self._front self._front = node # Update head node # Rear enqueue operation else: # Add node to the tail of the list self._rear.next = node node.prev = self._rear self._rear = node # Update tail node self._size += 1 # Update queue length def push_first(self, num: int): """Front enqueue""" self.push(num, True) def push_last(self, num: int): """Rear enqueue""" self.push(num, False) def pop(self, is_front: bool) -> int: """Dequeue operation""" if self.is_empty(): raise IndexError("Double-ended queue is empty") # Front dequeue operation if is_front: val: int = self._front.val # Temporarily store the head node value # Remove head node fnext: ListNode | None = self._front.next if fnext != None: fnext.prev = None self._front.next = None self._front = fnext # Update head node # Rear dequeue operation else: val: int = self._rear.val # Temporarily store the tail node value # Remove tail node rprev: ListNode | None = self._rear.prev if rprev != None: rprev.next = None self._rear.prev = None self._rear = rprev # Update tail node self._size -= 1 # Update queue length return val def pop_first(self) -> int: """Front dequeue""" return self.pop(True) def pop_last(self) -> int: """Rear dequeue""" return self.pop(False) def peek_first(self) -> int: """Access front element""" if self.is_empty(): raise IndexError("Double-ended queue is empty") return self._front.val def peek_last(self) -> int: """Access rear element""" if self.is_empty(): raise IndexError("Double-ended queue is empty") return self._rear.val def to_array(self) -> list[int]: """Return array for printing""" node = self._front res = [0] * self.size() for i in range(self.size()): res[i] = node.val node = node.next return res ``` === "C++" ```cpp title="linkedlist_deque.cpp" [class]{DoublyListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "Java" ```java title="linkedlist_deque.java" /* Double-linked list node */ class ListNode { int val; // Node value ListNode next; // Reference to the next node ListNode prev; // Reference to predecessor node ListNode(int val) { this.val = val; prev = next = null; } } /* Double-ended queue class based on double-linked list */ class LinkedListDeque { private ListNode front, rear; // Front node front, back node rear private int queSize = 0; // Length of the double-ended queue public LinkedListDeque() { front = rear = null; } /* Get the length of the double-ended queue */ public int size() { return queSize; } /* Determine if the double-ended queue is empty */ public boolean isEmpty() { return size() == 0; } /* Enqueue operation */ private void push(int num, boolean isFront) { ListNode node = new ListNode(num); // If the list is empty, make front and rear both point to node if (isEmpty()) front = rear = node; // Front enqueue operation else if (isFront) { // Add node to the head of the list front.prev = node; node.next = front; front = node; // Update head node // Rear enqueue operation } else { // Add node to the tail of the list rear.next = node; node.prev = rear; rear = node; // Update tail node } queSize++; // Update queue length } /* Front enqueue */ public void pushFirst(int num) { push(num, true); } /* Rear enqueue */ public void pushLast(int num) { push(num, false); } /* Dequeue operation */ private int pop(boolean isFront) { if (isEmpty()) throw new IndexOutOfBoundsException(); int val; // Front dequeue operation if (isFront) { val = front.val; // Temporarily store the head node value // Remove head node ListNode fNext = front.next; if (fNext != null) { fNext.prev = null; front.next = null; } front = fNext; // Update head node // Rear dequeue operation } else { val = rear.val; // Temporarily store the tail node value // Remove tail node ListNode rPrev = rear.prev; if (rPrev != null) { rPrev.next = null; rear.prev = null; } rear = rPrev; // Update tail node } queSize--; // Update queue length return val; } /* Front dequeue */ public int popFirst() { return pop(true); } /* Rear dequeue */ public int popLast() { return pop(false); } /* Access front element */ public int peekFirst() { if (isEmpty()) throw new IndexOutOfBoundsException(); return front.val; } /* Access rear element */ public int peekLast() { if (isEmpty()) throw new IndexOutOfBoundsException(); return rear.val; } /* Return array for printing */ 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_deque.cs" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "Go" ```go title="linkedlist_deque.go" [class]{linkedListDeque}-[func]{} ``` === "Swift" ```swift title="linkedlist_deque.swift" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "JS" ```javascript title="linkedlist_deque.js" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "TS" ```typescript title="linkedlist_deque.ts" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "Dart" ```dart title="linkedlist_deque.dart" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "Rust" ```rust title="linkedlist_deque.rs" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "C" ```c title="linkedlist_deque.c" [class]{DoublyListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "Kotlin" ```kotlin title="linkedlist_deque.kt" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "Ruby" ```ruby title="linkedlist_deque.rb" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` === "Zig" ```zig title="linkedlist_deque.zig" [class]{ListNode}-[func]{} [class]{LinkedListDeque}-[func]{} ``` ### 2. Implementation based on array As shown in Figure 5-9, similar to implementing a queue with an array, we can also use a circular array to implement a double-ended queue. === "ArrayDeque" { class="animation-figure" } === "pushLast()" { class="animation-figure" } === "pushFirst()" { class="animation-figure" } === "popLast()" { class="animation-figure" } === "popFirst()" { class="animation-figure" }Figure 5-9 Implementing Double-Ended Queue with Array for Enqueue and Dequeue Operations
The implementation only needs to add methods for "front enqueue" and "rear dequeue": === "Python" ```python title="array_deque.py" class ArrayDeque: """Double-ended queue class based on circular array""" def __init__(self, capacity: int): """Constructor""" self._nums: list[int] = [0] * capacity self._front: int = 0 self._size: int = 0 def capacity(self) -> int: """Get the capacity of the double-ended queue""" return len(self._nums) def size(self) -> int: """Get the length of the double-ended queue""" return self._size def is_empty(self) -> bool: """Determine if the double-ended queue is empty""" return self._size == 0 def index(self, i: int) -> int: """Calculate circular array index""" # Implement circular array by modulo operation # When i exceeds the tail of the array, return to the head # When i exceeds the head of the array, return to the tail return (i + self.capacity()) % self.capacity() def push_first(self, num: int): """Front enqueue""" if self._size == self.capacity(): print("Double-ended queue is full") return # Move the front pointer one position to the left # Implement front crossing the head of the array to return to the tail by modulo operation self._front = self.index(self._front - 1) # Add num to the front self._nums[self._front] = num self._size += 1 def push_last(self, num: int): """Rear enqueue""" if self._size == self.capacity(): print("Double-ended queue is full") return # Calculate rear pointer, pointing to rear index + 1 rear = self.index(self._front + self._size) # Add num to the rear self._nums[rear] = num self._size += 1 def pop_first(self) -> int: """Front dequeue""" num = self.peek_first() # Move front pointer one position backward self._front = self.index(self._front + 1) self._size -= 1 return num def pop_last(self) -> int: """Rear dequeue""" num = self.peek_last() self._size -= 1 return num def peek_first(self) -> int: """Access front element""" if self.is_empty(): raise IndexError("Double-ended queue is empty") return self._nums[self._front] def peek_last(self) -> int: """Access rear element""" if self.is_empty(): raise IndexError("Double-ended queue is empty") # Calculate rear element index last = self.index(self._front + self._size - 1) return self._nums[last] def to_array(self) -> list[int]: """Return array for printing""" # Only convert elements within valid length range res = [] for i in range(self._size): res.append(self._nums[self.index(self._front + i)]) return res ``` === "C++" ```cpp title="array_deque.cpp" [class]{ArrayDeque}-[func]{} ``` === "Java" ```java title="array_deque.java" /* Double-ended queue class based on circular array */ class ArrayDeque { private int[] nums; // Array used to store elements of the double-ended queue private int front; // Front pointer, pointing to the front element private int queSize; // Length of the double-ended queue /* Constructor */ public ArrayDeque(int capacity) { this.nums = new int[capacity]; front = queSize = 0; } /* Get the capacity of the double-ended queue */ public int capacity() { return nums.length; } /* Get the length of the double-ended queue */ public int size() { return queSize; } /* Determine if the double-ended queue is empty */ public boolean isEmpty() { return queSize == 0; } /* Calculate circular array index */ private int index(int i) { // Implement circular array by modulo operation // When i exceeds the tail of the array, return to the head // When i exceeds the head of the array, return to the tail return (i + capacity()) % capacity(); } /* Front enqueue */ public void pushFirst(int num) { if (queSize == capacity()) { System.out.println("Double-ended queue is full"); return; } // Move the front pointer one position to the left // Implement front crossing the head of the array to return to the tail by modulo operation front = index(front - 1); // Add num to the front nums[front] = num; queSize++; } /* Rear enqueue */ public void pushLast(int num) { if (queSize == capacity()) { System.out.println("Double-ended queue is full"); return; } // Calculate rear pointer, pointing to rear index + 1 int rear = index(front + queSize); // Add num to the rear nums[rear] = num; queSize++; } /* Front dequeue */ public int popFirst() { int num = peekFirst(); // Move front pointer one position backward front = index(front + 1); queSize--; return num; } /* Rear dequeue */ public int popLast() { int num = peekLast(); queSize--; return num; } /* Access front element */ public int peekFirst() { if (isEmpty()) throw new IndexOutOfBoundsException(); return nums[front]; } /* Access rear element */ public int peekLast() { if (isEmpty()) throw new IndexOutOfBoundsException(); // Calculate rear element index int last = index(front + queSize - 1); return nums[last]; } /* Return array for printing */ 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[index(j)]; } return res; } } ``` === "C#" ```csharp title="array_deque.cs" [class]{ArrayDeque}-[func]{} ``` === "Go" ```go title="array_deque.go" [class]{arrayDeque}-[func]{} ``` === "Swift" ```swift title="array_deque.swift" [class]{ArrayDeque}-[func]{} ``` === "JS" ```javascript title="array_deque.js" [class]{ArrayDeque}-[func]{} ``` === "TS" ```typescript title="array_deque.ts" [class]{ArrayDeque}-[func]{} ``` === "Dart" ```dart title="array_deque.dart" [class]{ArrayDeque}-[func]{} ``` === "Rust" ```rust title="array_deque.rs" [class]{ArrayDeque}-[func]{} ``` === "C" ```c title="array_deque.c" [class]{ArrayDeque}-[func]{} ``` === "Kotlin" ```kotlin title="array_deque.kt" [class]{ArrayDeque}-[func]{} ``` === "Ruby" ```ruby title="array_deque.rb" [class]{ArrayDeque}-[func]{} ``` === "Zig" ```zig title="array_deque.zig" [class]{ArrayDeque}-[func]{} ``` ## 5.3.3 Applications of double-ended queue The double-ended queue combines the logic of both stacks and queues, **thus, it can implement all their respective use cases while offering greater flexibility**. We know that software's "undo" feature is typically implemented using a stack: the system `pushes` each change operation onto the stack and then `pops` to implement undoing. However, considering the limitations of system resources, software often restricts the number of undo steps (for example, only allowing the last 50 steps). When the stack length exceeds 50, the software needs to perform a deletion operation at the bottom of the stack (the front of the queue). **But a regular stack cannot perform this function, where a double-ended queue becomes necessary**. Note that the core logic of "undo" still follows the Last-In-First-Out principle of a stack, but a double-ended queue can more flexibly implement some additional logic.