code_junkie

Can I Limit the depth of a Generic Stack?

Nov 13th, 2011
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.62 KB | None | 0 0
  1. public static void Trim<T> (this Stack<T> stack, int trimCount)
  2. {
  3. if (stack.Count <= trimCount)
  4. return;
  5.  
  6. stack = new
  7. Stack<T>
  8. (
  9. stack
  10. .ToArray()
  11. .Take(trimCount)
  12. );
  13. }
  14.  
  15. class DropOutStack<T>
  16. {
  17. private T[] items;
  18. private int top = 0;
  19. public DropOutStack(int capacity)
  20. {
  21. items = new T[capacity];
  22. }
  23.  
  24. public void Push(T item)
  25. {
  26. items[top] = item;
  27. top = (top + 1) % items.Length;
  28. }
  29. public T Pop()
  30. {
  31. top = (items.Length + top - 1) % items.Length;
  32. return items[top];
  33. }
  34. }
Add Comment
Please, Sign In to add comment