ex-col-03-santa/SantaClausInc/Collections/Stack.cs
MarcUs7i d3e489b99c Done with List&Stack
Added TargetCity and initialized it by the constructor in Sleigh.cs
2024-12-19 16:32:46 +01:00

66 lines
1.9 KiB
C#

using System.Diagnostics.CodeAnalysis;
namespace SantaClausInc.Collections;
/// <summary>
/// Represents a stack which can be used with a generic type
/// </summary>
/// <typeparam name="TValue">Type of the values stored in the stack</typeparam>
public sealed class Stack<TValue>
{
private Node<TValue>? _head;
/// <summary>
/// Creates a new instance of the <see cref="Stack{TValue}" />
/// </summary>
public Stack()
{
_head = null;
}
/// <summary>
/// Gets the number of items on the stack
/// </summary>
public int Count { get; private set; }
// uncomment this once the fields are implemented to avoid redundant nullability warnings
[MemberNotNullWhen(false, nameof(_head))]
private bool IsEmpty => _head == null;
/// <summary>
/// Adds an item on top of the stack
/// </summary>
/// <param name="value">Value to add</param>
public void Push(TValue value)
{
var newNode = new Node<TValue>(value);
Count++;
newNode.Next = _head; //get to root node
_head = newNode; //make the new node the head (the root node)
}
/// <summary>
/// Gets the top element on the stack without removing it.
/// If the stack is empty the default value for the <see cref="TValue" /> type is returned.
/// </summary>
/// <returns>Top element of the stack or default</returns>
public TValue? Peek() => _head != null ? _head.Data : default;
/// <summary>
/// Gets and removes the top element of the stack.
/// If the stack is empty the default value for the <see cref="TValue" /> type is returned.
/// </summary>
/// <returns>Top element of the stack or default</returns>
public TValue? Pop()
{
if (_head == null)
{
return default;
}
Count--;
var data = _head.Data;
_head = _head.Next;
return data;
}
}