code_junkie

Why isn't System&hellip;Stack<T> implemented as a Linked List?

Nov 13th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. public static Stack<T> Remove<T>(this Stack<T> stack, T item)
  2. {
  3. Stack<T> newStack = new Stack<T>();
  4.  
  5. EqualityComparer<T> eqc = EqualityComparer<T>.Default;
  6.  
  7. foreach( T newItem in stack.Reverse() )
  8. {
  9. if( !eqc.Equals(newItem, item) )
  10. {
  11. newStack.Push(newItem);
  12. }
  13. }
  14.  
  15. return newStack;
  16. }
  17. /// <summary>
  18. /// Returns a new Stack{T} with one or more items removed, based on the given predicate.
  19. /// </summary>
  20. /// <typeparam name="T"></typeparam>
  21. /// <param name="stack"></param>
  22. /// <param name="fnRemove"></param>
  23. /// <returns>The new stack.</returns>
  24. /// <remarks>
  25. /// We have to turn tricks in order to save the LIFO order of the pool
  26. /// since there is no built-in remove method since they implement a Stack internally
  27. /// as an array instead of a linked list. Maybe they have a good reason, I don't know...
  28. ///
  29. /// So, to fix this I'm just using a LINQ extension method to enumerate in reverse.
  30. /// </remarks>
  31. public static Stack<T> RemoveWhere<T>(this Stack<T> stack, Predicate<T> fnRemove)
  32. {
  33. Stack<T> newStack = new Stack<T>();
  34.  
  35. foreach( T newItem in stack.Reverse() )
  36. {
  37. /// Check using the caller's method.
  38. if( fnRemove(newItem) )
  39. {
  40. /// It's not allowed in the new stack.
  41. continue;
  42. }
  43. newStack.Push(newItem);
  44. }
  45.  
  46. return newStack;
  47. }
Add Comment
Please, Sign In to add comment