2022-04-01 21:02:39 +00:00
|
|
|
namespace C_.Datastructures.Stack
|
2022-03-26 22:38:49 +00:00
|
|
|
{
|
2022-03-28 22:16:33 +00:00
|
|
|
public class Stack<T>
|
2022-03-26 22:38:49 +00:00
|
|
|
{
|
2022-03-28 22:08:19 +00:00
|
|
|
internal StackNode<T>? Head { get; set; }
|
2022-03-28 21:41:24 +00:00
|
|
|
private int Count { get; set; } = 0;
|
2022-03-26 22:38:49 +00:00
|
|
|
|
2022-03-31 21:13:13 +00:00
|
|
|
public static Stack<T> Create()
|
|
|
|
{
|
2022-03-26 22:38:49 +00:00
|
|
|
//Create a new stack without a head
|
2022-03-28 21:41:24 +00:00
|
|
|
return new Stack<T>();
|
2022-03-26 22:38:49 +00:00
|
|
|
}
|
|
|
|
|
2022-04-14 19:40:52 +00:00
|
|
|
public static Stack<T> Create(T? value)
|
2022-03-31 21:13:13 +00:00
|
|
|
{
|
2022-03-26 22:38:49 +00:00
|
|
|
//Create a new Stack with a head
|
2022-03-31 21:13:13 +00:00
|
|
|
return new Stack<T>
|
|
|
|
{
|
2022-03-28 21:41:24 +00:00
|
|
|
Head = StackNode<T>.Create(value, default),
|
2022-03-26 22:38:49 +00:00
|
|
|
Count = 1
|
|
|
|
};
|
|
|
|
}
|
2022-03-28 22:08:19 +00:00
|
|
|
|
2022-04-14 19:40:52 +00:00
|
|
|
public void Push(T? value)
|
2022-03-31 21:13:13 +00:00
|
|
|
{
|
2022-03-31 20:55:17 +00:00
|
|
|
//Add an Item to the top of the stack
|
|
|
|
Count++;
|
2022-03-31 21:05:13 +00:00
|
|
|
Head = StackNode<T>.Create(value, Head);
|
2022-03-31 20:55:17 +00:00
|
|
|
return;
|
2022-03-28 22:08:19 +00:00
|
|
|
}
|
|
|
|
|
2022-03-31 21:13:13 +00:00
|
|
|
public T? Pop()
|
|
|
|
{
|
2022-03-31 20:32:42 +00:00
|
|
|
//Take the item off of the top of the stack
|
2022-03-28 22:08:19 +00:00
|
|
|
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;
|
2022-03-31 20:55:17 +00:00
|
|
|
if (Count == 0)
|
|
|
|
{
|
|
|
|
Head = default;
|
|
|
|
}
|
2022-03-28 22:08:19 +00:00
|
|
|
}
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
2022-03-31 21:13:13 +00:00
|
|
|
public T? Peek()
|
|
|
|
{
|
2022-03-31 20:32:42 +00:00
|
|
|
//View item on top of the stack
|
2022-03-28 22:08:19 +00:00
|
|
|
if (Count > 0)
|
|
|
|
{
|
|
|
|
return Head!.Value;
|
|
|
|
}
|
|
|
|
return default;
|
|
|
|
}
|
2022-04-17 21:17:53 +00:00
|
|
|
|
|
|
|
public int GetCount()
|
|
|
|
{//Return the number of items in the list
|
|
|
|
return Count;
|
|
|
|
}
|
2022-03-26 22:38:49 +00:00
|
|
|
}
|
|
|
|
}
|