Deque
A deque is a double-ended queue in which elements can be added to either the front or the back. Removal can also occur from either the front or back.
Since adding and deleting must be implemented on both sides, a doubly linked list can be used as the basis for implementation. Thus, each element in the deque will be represented by the following class:
1 2 3 4 5 6 7 8 9 10 | public class DoublyNode<T>{ public DoublyNode(T data) { Data = data; }
// FIXED: Changed ‘DoubleNode’ to match the actual class name ‘DoublyNode’ |
The deck class will be as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | using System;using System.Collections; using System.Collections.Generic;
|
Unlike the queue class, there are two methods defined here for adding and two for removing.
To add to the head of the queue, we reset the reference to the head variable:
1 2 3 4 5 6 7 8 9 10 11 12 | public void AddFirst(T data){ DoublyNode<T> node = new DoublyNode<T>(data);
|
Adding an element to the end of a deque causes a similar reset of the tail variable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public void AddLast(T data){ DoublyNode<T> node = new DoublyNode<T>(data);
|
When deleting from the beginning of a deck, you need to reset the reference to the first element:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public T RemoveFirst(){ // 1. Added head == null check to satisfy modern compiler null-safety analysis if (count == 0 || head == null) throw new InvalidOperationException(“The deque is empty.”);
if (count == 1)
|
When the last element is removed, the tail variable is reset to the second-to-last element:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public T RemoveLast(){ // 1. Added tail == null check to satisfy modern compiler null-safety analysis if (count == 0 || tail == null) throw new InvalidOperationException(“The deque is empty.”);
if (count == 1)
|
The algorithmic complexity of all methods for adding and removing from a deque is O(1).

Application of the deck:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Deque<string> usersDeck = new Deque<string>();usersDeck.AddFirst(“Alice”); usersDeck.AddLast(“Kate”); usersDeck.AddLast(“Tom”);
|
Console output:
Alice Kate Tom Removed: Alice Kate Tom
Explore More IT Terms
A
B
C
D
E
F
H
K
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is a GPU in a computer, in simple terms?
- What is Linux? The History of Linux
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- Which Linux distribution should you choose? A Linux distribution overview
