Queues
using System;
using System.Collections.Generic; // Required for using the List<T> class
public class Queue<T>
{
private List<T> elements = new List<T>();
// Method to add an item to the back of the queue
public void Enqueue(T item)
{
elements.Add(item);
}
// Method to remove and return the front item of the queue
public T Dequeue()
{
if (IsEmpty())
{
throw new InvalidOperationException("Queue is empty");
}
var item = elements[0];
elements.RemoveAt(0);
return item;
}
// Method to return the front item of the queue without removing it
public T Peek()
{
if (IsEmpty())
{
throw new InvalidOperationException("Queue is empty");
}
return elements[0];
}
// Method to check if the queue is empty
public bool IsEmpty()
{
return elements.Count == 0;
}
// Method to get the current size of the queue
public int Size()
{
return elements.Count;
}
}
class Program
{
static void Main()
{
var queue = new Queue<string>();
// Enqueue items into the queue
queue.Enqueue("Apple");
queue.Enqueue("Banana");
queue.Enqueue("Cherry");
// Peek at the front item
Console.WriteLine("Front item: " + queue.Peek());
// Dequeue an item from the queue
Console.WriteLine("Dequeued item: " + queue.Dequeue());
// Check the queue's current size
Console.WriteLine("Current queue size: " + queue.Size());
}
}Last updated
Was this helpful?