Ejercicio
Colecciones de colas
Objetivo
Cree una cola de cadenas, utilizando la clase Queue que ya existe en la plataforma DotNet.
Una vez creado, muestra todos los elementos almacenados en la cola.
Código de Ejemplo
// Importing the necessary namespace for collections and basic functionalities
using System; // For basic functionalities like Console
using System.Collections.Generic; // For using the Queue class
// Main program to demonstrate the Queue functionality
class Program
{
static void Main(string[] args)
{
// Create a Queue of strings
Queue queue = new Queue();
// Menu to allow user to interact with the queue
while (true)
{
Console.WriteLine("\nMenu:");
Console.WriteLine("1. Enqueue an element");
Console.WriteLine("2. Dequeue an element");
Console.WriteLine("3. Display the queue");
Console.WriteLine("4. Exit");
Console.Write("Enter your choice: ");
string choice = Console.ReadLine();
if (choice == "1")
{
// Prompt user to enter a string to enqueue into the queue
Console.Write("Enter a string to enqueue: ");
string element = Console.ReadLine();
queue.Enqueue(element); // Add the string to the queue
Console.WriteLine($"Enqueued: {element}");
}
else if (choice == "2")
{
// Dequeue an element from the queue
if (queue.Count > 0)
{
string dequeuedElement = queue.Dequeue(); // Remove and get the element from the front of the queue
Console.WriteLine($"Dequeued: {dequeuedElement}");
}
else
{
Console.WriteLine("Queue is empty! Cannot dequeue.");
}
}
else if (choice == "3")
{
// Display the current elements in the queue
if (queue.Count > 0)
{
Console.WriteLine("Queue contents:");
foreach (string item in queue)
{
Console.WriteLine(item); // Print each item in the queue
}
}
else
{
Console.WriteLine("Queue is empty.");
}
}
else if (choice == "4")
{
// Exit the program
break;
}
else
{
// Invalid choice
Console.WriteLine("Invalid choice. Please try again.");
}
}
}
}