|
Queues in C#
    
Queue is a Simple DataStucture which allows Insert/Remove of Items at one of the ends only.
It is basically called as FIFO (First In First Out) data structure.
Three main operations can be performed on a Queue and its elements:
· Enqueue adds an element to the end of the Queue.
· Dequeue removes the oldest element from the start of the Queue.
· Peek returns the oldest element from the start of the Queue but does not remove it from the Queue.
How to add to a queue?
By using Enqueue. Enqueue adds an element to stringQueue.
stringQueue.Enqueue("string#" + i.ToString());
How to remove from queue?
By using Dequeue.Dequeue removes the oldest element from stringQueue.
stringQueue.Dequeue();
How to get an element from the queue?
By using Peek. Peek views the first element in the stringQueue but doesn’t remove.
stringQueue.Peek();
The following example demonstrates a queue with strings.
using System;
using System.Collections.Generic;
namespace Queue
{
public class Tester
{
static void Main()
{
Queue stringQueue = new Queue();
// populate the array
for (int i = 0; i < 5; i++)
{
stringQueue.Enqueue("string#" + i.ToString());
}
// Display the Queue.
Console.Write("stringQueue values:\t");
PrintValues(stringQueue);
// Remove an element from the queue.
Console.WriteLine(
"\n(Dequeue)\t{0}", stringQueue.Dequeue());
// Display the Queue.
Console.Write("stringQueue values:\t");
PrintValues(stringQueue);
// Remove another element from the queue.
Console.WriteLine(
"\n(Dequeue)\t{0}", stringQueue.Dequeue());
// Display the Queue.
Console.Write("stringQueue values:\t");
PrintValues(stringQueue);
// View the first element in the
// Queue but do not remove.
Console.WriteLine(
"\n(Peek) \t{0}", stringQueue.Peek());
// Display the Queue.
Console.Write("stringQueue values:\t");
PrintValues(stringQueue);
}
public static void PrintValues(IEnumerable myCollection)
{
IEnumerator myEnumerator =
myCollection.GetEnumerator();
while (myEnumerator.MoveNext())
Console.Write("{0} ", myEnumerator.Current);
Console.WriteLine();
}
}
}
|
Downloads
The sample code can be downloaded from below link. The code is complied with Microsoft Visual C# 2005.
|