Introduction: Queue is an abstract data type.
It serves as a collection of elements and follow FIFO (First in first out)
pattern. So first element added to the queue will be the first one to be
removed.
It has main 2 operations
Enqueue: This operation adds
an element to the queue
Dequeue: It removes the
item from the beginning of the queue.
using System;
namespace DataStructure
{
public interface IQueue<T>
{
void Enqueue(T item);
T Dequeue();
void Print();
}
public class Queue<T> : IQueue<T>
{
T[] _items = new T[10];
int _rear=-1;
int _front =-1;
public void Enqueue(T item)
{
if (_rear == 9)
Console.WriteLine("queue overflow.");
else
{
if (_front
== -1) _front++;
_items[++_rear] = item;
}
}
public T Dequeue()
{
if (_front == -1 ||
_front > _rear)
{
Console.WriteLine("Queue underflow.");
throw new
Exception("Queue underflow");
}
else
{
return
_items[_front++];
}
}
public void Print()
{
if(_front==-1)
Console.WriteLine("queue is empty");
else
{
for (int i
= _front; i <= _rear; i++)
{
Console.WriteLine("Item {0}",_items[i]);
}
}
}
}
public class Program
{
public static void Main(string[] args)
{
var queue = new
Queue<int>();
queue.Enqueue(100);
queue.Enqueue(101);
queue.Enqueue(150);
queue.Print();
Console.WriteLine("item dequeue:{0}", queue.Dequeue());
queue.Print();
queue.Enqueue(200);
queue.Print();
Console.ReadKey();
}
}
}
No comments:
Post a Comment