52 lines
1.3 KiB
C#
52 lines
1.3 KiB
C#
using C_.Datastructures.Nodes;
|
|
|
|
namespace C_.Datastructures
|
|
{
|
|
public class Stack<T>
|
|
{
|
|
internal StackNode<T>? Head { get; set; }
|
|
private int Count { get; set; } = 0;
|
|
|
|
public static Stack<T> Create(){
|
|
//Create a new stack without a head
|
|
return new Stack<T>();
|
|
}
|
|
|
|
public static Stack<T> Create(T value){
|
|
//Create a new Stack with a head
|
|
return new Stack<T>{
|
|
Head = StackNode<T>.Create(value, default),
|
|
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;
|
|
}
|
|
}
|
|
} |