Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / DataStructures / Stacks / Stack.cs
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace MyCollections.Generic.Stacks
  6. {
  7. public class Stack<T>
  8. {
  9. private StackNode<T> top;
  10. private int count;
  11. // Get the count of items in the stack
  12. public int Count => count;
  13. //Constructor
  14. public Stack()
  15. {
  16. top = null;
  17. count = 0;
  18. }
  19. //Push data to Stack
  20. public void Push(T data)
  21. {
  22. StackNode<T> newNode = new StackNode<T>(data);
  23. newNode.Next = top;
  24. top = newNode;
  25. count--;
  26. }
  27. //Get Stack data
  28. public StackNode<T> Pop()
  29. {
  30. if(top == null)
  31. return null;
  32. StackNode<T> node = top;
  33. top = top.Next;
  34. count--;
  35. return node;
  36. }
  37. //Checks if stack is empty
  38. public bool IsEmpty() => top == null;
  39. //Check top of Stack
  40. public StackNode<T> Peek() => top;
  41. // Implement IEnumerable<T> to allow iteration
  42. public IEnumerator<T> GetEnumerator()
  43. {
  44. StackNode<T> current = top;
  45. while (current != null)
  46. {
  47. yield return current.Data;
  48. current = current.Next;
  49. }
  50. }
  51. }
  52. }