CappedStack.cs 980 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. /// <summary>
  4. /// Extended version of List used to give stack functionality, but with a maximum capacity.
  5. /// </summary>
  6. public class CappedStack<T> : List<T>
  7. {
  8. public int maxValues;
  9. public CappedStack(int max)
  10. {
  11. maxValues = max;
  12. }
  13. /// <summary>
  14. /// Adds the object to the top of the stack. If stack is longer than maxValues,
  15. /// removes the oldest item.
  16. /// </summary>
  17. /// <param name="val">Object to go on top of the stack.</param>
  18. public void Push(T val)
  19. {
  20. Add(val);
  21. if (Count > maxValues)
  22. {
  23. RemoveAt(0);
  24. }
  25. }
  26. /// <summary>
  27. /// Returns the item on top of the stack and removes it.
  28. /// </summary>
  29. /// <returns>Top stack item. </returns>
  30. public T Pop()
  31. {
  32. T val = this[Count - 1];
  33. RemoveAt(Count - 1);
  34. return val;
  35. }
  36. }