Added + Completed Queue Datastructure

This commit is contained in:
Luke Else 2022-03-31 22:06:25 +01:00
parent 703826c8a6
commit fc832edb9d
2 changed files with 131 additions and 1 deletions

View File

@ -0,0 +1,73 @@
using System.Linq;
using C_.Datastructures.Nodes;
namespace C_.Datastructures
{
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;
}
}
}

View File

@ -21,6 +21,13 @@ Console.WriteLine("Hello, World!");
// DoublyLinkedList<int> list = new DoublyLinkedList<int>(); // DoublyLinkedList<int> list = new DoublyLinkedList<int>();
// list.Append(1); // list.Append(1);
@ -40,10 +47,60 @@ Console.WriteLine("Hello, World!");
// Console.Write($"{list[6]} \n"); // Console.Write($"{list[6]} \n");
Stack<int> test = Stack<int>.Create();
//Stack<int> stack = Stack<int>.Create();
//stack.Push(1);
//stack.Push(2);
//stack.Push(3);
//stack.Push(4);
//stack.Push(5);
//stack.Push(6);
//Console.WriteLine(stack.Peek());
//stack.Pop();
//stack.Push(7);
//stack.Pop();
//stack.Pop();
//stack.Pop();
//stack.Pop();
//stack.Pop();
//stack.Pop();
//Queue<int> queue = Queue<int>.Create();
//queue.Push(1);
//queue.Push(2);
//queue.Push(3);
//queue.Push(4);
//queue.Push(5);
//queue.Push(6);
//Console.WriteLine(queue.Peek());
//queue.Pop();
//queue.Push(7);
//queue.Pop();
//queue.Pop();
//queue.Pop();
//queue.Pop();
//queue.Pop();
//queue.Pop();
Console.ReadLine(); Console.ReadLine();