From fdd1461e3a26ef63b1ef44e24137d6a50f2c2b31 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Mon, 28 Mar 2022 23:08:19 +0100 Subject: [PATCH] Added Push, Pop and Peek methods to Stack --- C#/Datastructures/Stack.cs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/C#/Datastructures/Stack.cs b/C#/Datastructures/Stack.cs index fa8ec31..06d6f16 100644 --- a/C#/Datastructures/Stack.cs +++ b/C#/Datastructures/Stack.cs @@ -4,7 +4,7 @@ namespace C_.Datastructures { internal class Stack { - public StackNode? Head { get; set; } + internal StackNode? Head { get; set; } private int Count { get; set; } = 0; public Stack Create(){ @@ -19,5 +19,34 @@ namespace C_.Datastructures Count = 1 }; } + + public void Push(T value){ + //Add an Item to the end of the list + if (Count > 0) + { + Count++; + Head = StackNode.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; + } } } \ No newline at end of file