![]()
Article posted by
Gajananbok on 12/1/2011 | Views: 2910 | Category:
C# | Level: Beginner |
Points: 250
If you found
plagiarised (copied) or inappropriate content,
please
let us know the original source along with your correct email id (to communicate) for further action.
This article demonstrates how to implement queue in C# with the help of easy examples. Queue is a data structure element where elements are in form FIFO.
Queue:
Queues are dynamic
collections which have some concept of order. A Queue is a collection where elements are processed first in, first out
(FIFO). The item is put first in the queue is read first. The item in the end
is read last.
Priority queue : A queuing policy in which each
member has a priority determined by external factors. The member with the
highest priority is the first to be removed.
Real life Example
of queues –
1) Patients waiting outside the doctor's
clinic: The patient who comes first visits the
doctor first, and the patient who comes last visits the doctor last. Therefore,
it follows the first-in-first-out (FIFO) strategy of queue.
2) Queue in the Bank
3) Queue at the bus
stand
4) Queue at the Ration
shop
Examples of queues
in Software systems :
1) 1) Print jobs waiting to be processed in a print
queue
2) 2) A thread waiting for the CPU in a round-robin
fashion.
Often there are queues
where the elements processed differ in their priority. For example, in the
queue at the Bank, Gold card customers are processed before common customers.
Here, multiple queues can be used, one queue for every priority. In the bank
this can easily be found out, because there are separate queues for Gold card
and common customers. You can have an array or a list of queues where on item
in the array stands for a priority. Within every array item there is a queue,
where processing happens with the FIFO principle.
Implementing
classes and Interfaces :
In C# queue is
implemented with Queue<T> class in the namespace
System.Collections.Generic. It implements the interfaces IEnumerable &
ICollection.
Some useful methods of queue :
1) To create a queue:
Queue<int> p = new
Queue<int>();
2) To add element to
it :
p.Enqueue(i * 10);
3) To remove element
from queue :
p.Dequeue( );
4) To count total elements in queue:
p.Count;
using System;
using System.Collections.Generic;
namespace ConsoleApplication17
{
class Class1
{
public static void Main()
{
int i;
Queue<int> p = new Queue<int>();
for (i = 0; i < 5; i++)
{
p.Enqueue(i * 10);
}
Console.WriteLine("Total elements : " + p.Count);
Console.WriteLine("Elements is queue are :");
for (i = 0; i < 5; i++)
{
Console.WriteLine("Element {0}: {1} ", i, p.Dequeue());
}
Console.WriteLine("Total elements : "+ p.Count);
}
}
}
Output :
If you like this article, subscribe to our
RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.
Found interesting? Add this to: