Group
Dynamic Memory Management in C#
Objective
1. Create a Queue class that supports integer values.
2. Implement the methods Enqueue (to add elements), Dequeue (to remove elements), and Peek (to see the front element without removing it).
3. Handle edge cases, such as attempting to remove an element from an empty queue.
4. Demonstrate the functionality by adding, removing, and peeking elements in the queue.
In this exercise, you need to implement a queue in C#. A queue is a data structure that follows the FIFO (First In, First Out) principle, meaning the first element to enter is the first one to exit. In this exercise, you will need to create a class for the queue, allowing you to insert elements at the end of the queue and remove elements from the front. The goal of this exercise is to familiarize yourself with data structures in C# and how to manage them efficiently.
Example C# Exercise
Show C# Code
using System;
using System.Collections.Generic;
class CustomQueue
{
// List to store queue elements
private List queue;
// Constructor to initialize the queue
public CustomQueue()
{
queue = new List();
}
// Method to add an element to the end of the queue
public void Enqueue(int item)
{
queue.Add(item);
Console.WriteLine($"Enqueued: {item}");
}
// Method to remove and return the front element of the queue
public int Dequeue()
{
if (queue.Count == 0)
{
throw new InvalidOperationException("Queue is empty.");
}
int frontItem = queue[0];
queue.RemoveAt(0);
Console.WriteLine($"Dequeued: {frontItem}");
return frontItem;
}
// Method to return the front element without removing it
public int Peek()
{
if (queue.Count == 0)
{
throw new InvalidOperationException("Queue is empty.");
}
return queue[0];
}
// Method to check if the queue is empty
public bool IsEmpty()
{
return queue.Count == 0;
}
}
class Program
{
static void Main()
{
// Create an instance of the CustomQueue class
CustomQueue queue = new CustomQueue();
// Add elements to the queue
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
// Peek at the front element without removing it
Console.WriteLine($"Front element (Peek): {queue.Peek()}");
// Remove elements from the queue
queue.Dequeue();
queue.Dequeue();
// Peek again after dequeuing some elements
Console.WriteLine($"Front element after dequeuing (Peek): {queue.Peek()}");
// Remove the last element
queue.Dequeue();
// Check if the queue is empty
Console.WriteLine($"Is the queue empty? {queue.IsEmpty()}");
}
}
Output
Enqueued: 10
Enqueued: 20
Enqueued: 30
Front element (Peek): 10
Dequeued: 10
Dequeued: 20
Front element after dequeuing (Peek): 30
Dequeued: 30
Is the queue empty? True