Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / DataStructures / Stacks / Stack.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MyCollections.Generic.Stacks
{
    public class Stack<T>
    {
        private StackNode<T> top;
        private int count;

        // Get the count of items in the stack
        public int Count => count;

        //Constructor
        public Stack()
        {
            top = null;
            count = 0;
        }

        //Push data to Stack
        public void Push(T data)
        {
            StackNode<T> newNode = new StackNode<T>(data);
            
            newNode.Next = top;
            top = newNode;
            count--;
        }

        //Get Stack data
        public StackNode<T> Pop()
        {
            if(top == null)
                return null;

            StackNode<T> node = top;
            top = top.Next;
            count--;
            return node;
        }

        //Checks if stack is empty
        public bool IsEmpty() => top == null;

        //Check top of Stack
        public StackNode<T> Peek() => top;


        // Implement IEnumerable<T> to allow iteration
        public IEnumerator<T> GetEnumerator()
        {
            StackNode<T> current = top;
            while (current != null)
            {
                yield return current.Data;
                current = current.Next;
            }
        }
    }
}