Queue
A queue is a data structure that operates on the FIFO (First In First Out) principle. When a new element is added, it is placed at the end of the queue, or its tail, and when removed, it is placed at the beginning of the queue, or its head.
A common example of a queue is a typical hospital queue, where new patients stand at the end of the queue, and new patients are admitted from the beginning of the queue.
To implement the queue, we will again use an element class that contains the data itself and a reference to the next element:
1 2 3 4 5 6 7 8 9 | public class Node<T>{ // 1. Made the constructor data parameter nullable to match the property if T can be null public Node(T data) { Data = data; Next = null; // 2. Explicitly initializing Next to null for clarity }
// 3. Marked Next as nullable (Node<T>?) to explicitly show it can be null at the end of the list |
The queue class itself will look like this:
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 | using System;using System.Collections; using System.Collections.Generic;
|
To add to the queue, we need to reset the reference to the last element tail:
1 2 3 4 5 6 7 8 9 10 11 | public void Enqueue(T data){ Node<T> node = new Node<T>(data);
count++; |
When deleting, the reference to the first element must be reset. Since the first element is deleted, the next element becomes the new first element:
1 2 3 4 5 6 7 8 9 | public T Dequeue(){ // 1. Better practice to check if the head itself is null alongside the count if (count == 0 || head == null) throw new InvalidOperationException(“Queue is empty.”);
|
The complexity of the algorithms for adding and removing from the queue is O(1).

Using the queue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Queue<string> queue = new Queue<string>();queue.Enqueue(“Kate”); queue.Enqueue(“Sam”); queue.Enqueue(“Alice”); queue.Enqueue(“Tom”);
|
Console output:
Kate Sam Alice Tom Extracted item: Kate Sam Alice 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
