Added Push, Pop and Peek methods to Stack

This commit is contained in:
Luke Else 2022-03-28 23:08:19 +01:00
parent f263a14170
commit fdd1461e3a

View File

@ -4,7 +4,7 @@ namespace C_.Datastructures
{ {
internal class Stack<T> internal class Stack<T>
{ {
public StackNode<T>? Head { get; set; } internal StackNode<T>? Head { get; set; }
private int Count { get; set; } = 0; private int Count { get; set; } = 0;
public Stack<T> Create(){ public Stack<T> Create(){
@ -19,5 +19,34 @@ namespace C_.Datastructures
Count = 1 Count = 1
}; };
} }
public void Push(T value){
//Add an Item to the end of the list
if (Count > 0)
{
Count++;
Head = StackNode<T>.Create(value, Head);
return;
}
}
public T? Pop(){
T? value = default;
if (Count > 0)
{//Assign the default value if there are any items left in the stack
Count--;
value = Head!.Value;
Head = Head.Next;
}
return value;
}
public T? Peek(){
if (Count > 0)
{
return Head!.Value;
}
return default;
}
} }
} }