2022-04-01 21:02:39 +00:00
|
|
|
|
namespace C_.Datastructures.Queue
|
2022-03-31 21:06:25 +00:00
|
|
|
|
{
|
|
|
|
|
internal class Queue<T>
|
|
|
|
|
{
|
|
|
|
|
internal QueueNode<T>? Head { get; set; }
|
|
|
|
|
internal QueueNode<T>? Tail { get; set; }
|
|
|
|
|
private int Count { get; set; } = 0;
|
|
|
|
|
|
|
|
|
|
public static Queue<T> Create()
|
|
|
|
|
{
|
|
|
|
|
//Create a new queue without a head / tail
|
|
|
|
|
return new Queue<T>();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static Queue<T> Create(T value)
|
|
|
|
|
{
|
|
|
|
|
//Create a new Queue with a head + tail
|
|
|
|
|
QueueNode<T> newNode = QueueNode<T>.Create(value, default);
|
|
|
|
|
return new Queue<T>
|
|
|
|
|
{
|
|
|
|
|
Head = newNode,
|
|
|
|
|
Tail = newNode,
|
|
|
|
|
Count = 1
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Push(T value)
|
|
|
|
|
{
|
|
|
|
|
//Add an Item to the end of the Queue
|
|
|
|
|
Count++;
|
|
|
|
|
if (Count > 1)
|
|
|
|
|
{
|
|
|
|
|
Tail!.Next = QueueNode<T>.Create(value, default);
|
|
|
|
|
Tail = Tail!.Next;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
Head = QueueNode<T>.Create(value, default);
|
|
|
|
|
Tail = Head;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public T? Pop()
|
|
|
|
|
{
|
|
|
|
|
//Take the item off the front of the queue
|
|
|
|
|
T? value = default;
|
|
|
|
|
if (Count > 0)
|
|
|
|
|
{//Assign the default value if there are any items left in the Queue
|
|
|
|
|
Count--;
|
|
|
|
|
value = Head!.Value;
|
|
|
|
|
Head = Head.Next;
|
|
|
|
|
if (Count == 0)
|
|
|
|
|
{
|
|
|
|
|
Head = default;
|
|
|
|
|
Tail = Head;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public T? Peek()
|
|
|
|
|
{
|
|
|
|
|
//View item at the front of the Queue
|
|
|
|
|
if (Count > 0)
|
|
|
|
|
{
|
|
|
|
|
return Head!.Value;
|
|
|
|
|
}
|
|
|
|
|
return default;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|