C# Queue with Examples Last Updated : 31 Jan, 2025 Comments Improve Suggest changes Like Article Like Report A Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.Key Features:FIFO Behavior: The first element added is the first to be removed.Dynamic Size: A queue can grow or shrink as needed.Thread Safety: The Queue class is not thread-safe by default. Use ConcurrentQueue for thread-safe operations.Common Operations:Enqueue: Add an element to the queue.Dequeue: Remove and return the first element.Peek: View the first element without removing it.Contains: Check if an element exists in the queue. Example: This example demonstrates how to use a Queue in C# by enqueueing elements and then dequeuing them in FIFO (First-in-first-out ) order. C# // C# program to demonstrates how to use Queue using System; using System.Collections.Generic; class Geeks { public static void Main(string[] args) { // Create a new queue Queue<int> q = new Queue<int>(); // Enqueue elements into the queue q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(4); // Dequeue elements from the queue while (q.Count > 0) { Console.WriteLine(q.Dequeue()); } } } Output1 2 3 4 Hierarchy of Queue Class The Queue class implements the IEnumerable, ICollection, and ICloneable interfaces.When we add an item in the list, it is called enqueue.When we remove an item, it is called dequeue.Queue accepts null as a valid value for reference types.As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array.In Queue, we are allowed to store duplicate elements.The capacity of a Queue is the number of elements the Queue can hold.Creating a QueueQueue class has four constructors which are used to create the queue which are as follows:Queue(): This constructor is used to create an instance of the Queue class which is empty and having the default initial capacity, and uses the default growth factor.Queue(ICollection): This constructor is used to create an instance of Queue class which contains elements copied from the specified collection, has the same initial capacity as the number of elements copied, and uses the default growth factor.Queue(Int32): This constructor is used to create an instance of the Queue class which is empty and having specified initial capacity, and uses the default growth factor.Queue(Int32, Single): This constructor is used to create an instance of Queue class which is empty and having specified initial capacity, and uses the specified growth factor.Let’s see how to create an Queue using Queue() constructor:Step 1: Include System.Collections namespace in your program with the help of using keywordusing System.Collections;Step 2: Create a Stack using Stack classQueue q = new Queue();Performing Various Operations on Queue1. Adding Elements: We use Enqueue() method to insert elements in a Queue.Example: This example demonstrates how to create a queue in C# and add various elements to it using the Enqueue() method, then access and display the elements using a foreach loop. C# // C# program to demonstrate how to // create and add elements into a queue using System; using System.Collections; class Geeks { public static void Main() { // Create a queue // Using Queue class Queue q = new Queue(); // Adding elements to the Queue // Using Enqueue method q.Enqueue("Geeks"); q.Enqueue("geeksforgeeks"); q.Enqueue(null); q.Enqueue(1); q.Enqueue(10.0); // Accessing the elements // of q Queue // Using foreach loop foreach(var e in q) { Console.WriteLine(e); } } } OutputGeeks geeksforgeeks 1 10 2. Remove Elements: The Queue class provides two different methods to remove elements and the methods are:Clear() Method: The Clear()is used to remove the objects from the queue.Dequeue() Method: The Dequeue() removes the beginning element of the queue.Example: This example displays the contents of the Queue before and after removal. C# // C# Program to remove // elements from a queue using System; using System.Collections.Generic; class Geeks { public static void Main(string[] args) { // Initialize a queue Queue<string> q = new Queue<string>(); // Inserting elements into the // queue using Enqueue() q.Enqueue("Geeks"); q.Enqueue("For"); q.Enqueue("Geeks"); q.Enqueue("For"); // Initial queue Console.WriteLine("Initial queue: "); foreach(var item in q) { Console.WriteLine(item); } // Removing the front element q.Dequeue(); // Final queue after removal Console.WriteLine("\nUpdated queue after Dequeue:"); foreach(var item in q) { Console.WriteLine(item); } } } OutputInitial queue: Geeks For Geeks For Updated queue after Dequeue: For Geeks For 3. Get the Topmost Element of the Queue: The Queue class provides two different methods to find the topmost element of the Queue and the methods are listed below:Peek() Method: The Peek() method returns the object at the beginning of the Queue without removing it.Dequeue() Method: The Dequeue() method returns the object at the beginning of the Queue with modification means this method remove the topmost element of the queue.Example: This example demonstrates how to peek at the topmost element of a Queue. C# // C# Program to get the // front element of the Queue using System; using System.Collections.Generic; class Geeks { public static void Main(string[] args) { // Create a new queue of integers Queue<int> q = new Queue<int>(); // Enqueue elements into the queue q.Enqueue(10); q.Enqueue(20); q.Enqueue(30); // Checking if the queue is not empty before // accessing the front element if (q.Count > 0) { // Peek() returns the frontmost element without // removing it int f = q.Peek(); Console.WriteLine( "The frontmost element in the queue is: " + f); } else { Console.WriteLine("The queue is empty."); } } } OutputThe frontmost element in the queue is: 10 4. Check the Availability of Elements in the Queue: Queue class provide Contains() method to check if the element is present in the Queue or not.Example: This program demonstrates how to check if the specified element are present in a Queue using the contains() method. C# // C# Program to check the // availability of elements in the queue using System; using System.Collections.Generic; class Geeks { public static void Main(string[] args) { // Create a new queue of integers Queue<int> q = new Queue<int>(); // Enqueue elements into the queue q.Enqueue(10); q.Enqueue(20); q.Enqueue(30); // Check if the element 20 is present in the queue Console.WriteLine( "The element 20 is present in the queue: " + q.Contains(20)); Console.WriteLine( "The element 100 is present in the queue: " + q.Contains(100)); } } OutputThe element 20 is present in the queue: True The element 100 is present in the queue: False Generic Stack vs Non-Generic QueueGeneric QueueNon-Generic QueueGeneric queue is defined under System.Collections.Generic namespace.Non-Generic queue is defined under System.Collections namespace.Generic queue can only store same type of elements.Non-Generic queue can store same type or different types of elements.There is a need to define the type of the elements in the queue.There is no need to define the type of the elements in the queue.It is type- safe.It is not type-safe. Comment More infoAdvertise with us Next Article Implementation of Queue in Javascript ankita_saini Follow Improve Article Tags : C# CSharp-Queue-Class CSharp-Collections-Namespace CSharp-Collections-Queue Similar Reads Queue Data Structure A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems 2 min read Introduction to Queue Data Structure Queue is a linear data structure that follows FIFO (First In First Out) Principle, so the first element inserted is the first to be popped out. FIFO Principle in Queue:FIFO Principle states that the first element added to the Queue will be the first one to be removed or processed. So, Queue is like 5 min read Introduction and Array Implementation of Queue Similar to Stack, Queue is a linear data structure that follows a particular order in which the operations are performed for storing data. The order is First In First Out (FIFO). One can imagine a queue as a line of people waiting to receive something in sequential order which starts from the beginn 2 min read Queue - Linked List Implementation In this article, the Linked List implementation of the queue data structure is discussed and implemented. Print '-1' if the queue is empty.Approach: To solve the problem follow the below idea:we maintain two pointers, front and rear. The front points to the first item of the queue and rear points to 8 min read Applications, Advantages and Disadvantages of Queue A Queue is a linear data structure. This data structure follows a particular order in which the operations are performed. The order is First In First Out (FIFO). It means that the element that is inserted first in the queue will come out first and the element that is inserted last will come out last 5 min read Different Types of Queues and its Applications Introduction : A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In this article, the diff 8 min read Queue implementation in different languagesQueue in C++ STLIn C++, queue container follows the FIFO (First In First Out) order of insertion and deletion. According to it, the elements that are inserted first should be removed first. This is possible by inserting elements at one end (called back) and deleting them from the other end (called front) of the dat 4 min read Queue Interface In JavaThe Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features:Most implementations, like PriorityQueue, do not allow null elements.Implementation Class 11 min read Queue in PythonLike a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. Operations 6 min read C# Queue with ExamplesA Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.Key Features:FIF 6 min read Implementation of Queue in JavascriptA Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are inserted at the rear and removed from the front.Queue Operationsenqueue(item) - Adds an element to the end of the queue.dequeue() - Removes and returns the first element from the queue.peek() - Ret 7 min read Queue in Go LanguageA queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). Now if you are familiar with other programming languages like C++, Java, and Python then there are inbuilt queue libraries that can be used for the implementat 4 min read Queue in ScalaA queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change. In Scala, Q 3 min read Some question related to Queue implementationImplementation of Deque using doubly linked listA Deque (Double-Ended Queue) is a data structure that allows adding and removing elements from both the front and rear ends. Using a doubly linked list to implement a deque makes these operations very efficient, as each node in the list has pointers to both the previous and next nodes. This means we 9 min read Queue using StacksGiven a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations.Table of ContentBy Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Making 11 min read implement k Queues in a single arrayGiven an array of size n, the task is to implement k queues using the array.enqueue(qn, x) : Adds the element x into the queue number qn dequeue(qn, x) : Removes the front element from queue number qn isFull(qn) : Checks if the queue number qn is fullisEmpty(qn) : Checks if the queue number qn is em 15+ min read LRU Cache - Complete TutorialWhat is LRU Cache? Cache replacement algorithms are efficiently designed to replace the cache when the space is full. The Least Recently Used (LRU) is one of those algorithms. As the name suggests when the cache memory is full, LRU picks the data that is least recently used and removes it in order t 8 min read Easy problems on QueueDetect cycle in an undirected graph using BFSGiven an undirected graph, the task is to determine if cycle is present in it or not.Examples:Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]]Undirected Graph with 5 NodeOutput: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 1 â 0.Input: V = 4, edges[][] = [[0, 1], [1, 6 min read Breadth First Search or BFS for a GraphGiven a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Traversing directory in Java using BFSGiven a directory, print all files and folders present in directory tree rooted with given directory. We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from qu 2 min read Vertical Traversal of a Binary TreeGiven a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree.Examples: Input:Output: [[4], [2], [1, 5, 6], [3, 8] 10 min read Print Right View of a Binary TreeGiven a Binary Tree, the task is to print the Right view of it. The right view of a Binary Tree is a set of rightmost nodes for every level.Examples: Example 1: The Green colored nodes (1, 3, 5) represents the Right view in the below Binary tree. Example 2: The Green colored nodes (1, 3, 4, 5) repre 15+ min read Find Minimum Depth of a Binary TreeGiven a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi 15 min read Check whether a given graph is Bipartite or notGiven a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex i 8 min read Intermediate problems on QueueFlatten a multilevel linked list using level order traversalGiven a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own to produce a multilevel linked list. Given the head of the first level of the list. The task is to fla 9 min read Level with maximum number of nodesGiven a binary tree, the task is to find the level in a binary tree that has the maximum number of nodes. Note: The root is at level 0.Examples: Input: Binary Tree Output : 2Explanation: Input: Binary tree Output:1Explanation Using Breadth First Search - O(n) time and O(n) spaceThe idea is to traver 12 min read Find if there is a path between two vertices in a directed graphGiven a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.Example: Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]Input : src = 1, dest = 3Output: YesExplanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : src = 0, dest = 11 min read All nodes between two given levels in Binary TreeGiven a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1.Example: Input: Binary tree, l = 2, h = 3Output 8 min read Find next right node of a given keyGiven a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return NULL. Expected time complexity is O(n) where n is the number of nodes in the given binary tree.Example:Input: root = [10 2 6 8 4 N 5] and key = 2Output: 6Explanation 15+ min read Minimum steps to reach target by a Knight | Set 1Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.Examples: Input: KnightknightPosition: (1, 3) , targetPosition: (5, 0)Output: 3Explanation: In above diagr 9 min read Islands in a graph using BFSGiven an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in 15+ min read Level order traversal line by line (Using One Queue)Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line.Example:Input:Output:12 34 5Table of Content[Expected Approach â 1] Using Queue with delimiter â O(n) Time and O(n) Space[Expected Approach â 2] Using Queue without delimiter â O(n) Time and O(n) Space[Expected 12 min read First non-repeating character in a streamGiven an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc 15+ min read Like