Queue Implementation in C#

1. Introduction

A Queue is a linear data structure that follows the First In First Out (FIFO) principle. This means that the first element added to the queue will be the first element to be removed. Conceptually, it can be likened to a real-life queue or line; the first person to join the queue is the first to leave. In computing, queues are used in various algorithms, task scheduling, order processing, and many other processes.

2. Implementation Steps

1. Create a class for the Queue.

2. Implement methods for basic operations:

- Enqueue: Add an item to the end of the queue.

- Dequeue: Remove and return the front item from the queue.

- Peek: View the front item without removing it.

- IsEmpty: Check if the queue is empty.

3. Test the queue with these operations to ensure it works correctly.

3. Implementation in C#

using System;
using System.Collections.Generic;
public class Queue<T> {
    private List<T> elements = new List<T>();
    // Enqueue item to the end of the queue
    public void Enqueue(T item) {
        elements.Add(item);
    }
    // Dequeue item from the front of the queue
    public T Dequeue() {
        if (IsEmpty()) {
            throw new InvalidOperationException("Queue is empty");
        }
        var item = elements[0];
        elements.RemoveAt(0);
        return item;
    }
    // Peek at the front item without removing it
    public T Peek() {
        if (IsEmpty()) {
            throw new InvalidOperationException("Queue is empty");
        }
        return elements[0];
    }
    // Check if the queue is empty
    public bool IsEmpty() {
        return elements.Count == 0;
    }
}
public class Program {
    public static void Main() {
        Queue<int> queue = new Queue<int>();
        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(3);
        Console.WriteLine(queue.Peek());  // Should print 1
        Console.WriteLine(queue.Dequeue());   // Should print 1
        Console.WriteLine(queue.Peek());  // Should print 2
    }
}

Output:

1
1
2

Explanation:

1. A generic Queue class is created to allow queues of any type to be instantiated.

2. The Enqueue method adds an item to the end of the internal list, which represents the end of the queue.

3. The Dequeue method checks if the queue is empty. If it's not, it removes and returns the first item from the list (front of the queue). If the queue is empty, an exception is thrown.

4. The Peek method returns the first item from the list without removing it, allowing you to see the front of the queue.

5. The IsEmpty method returns a boolean indicating whether the internal list (and thus the queue) is empty.

6. In the Program class, we test the implementation by enqueuing numbers into the queue, peeking to see the front element, and dequeuing to remove the front element.

This provides a detailed understanding of the Queue implementation in C#.


Comments