Stack.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. namespace JsUtil
  7. {
  8. template <
  9. class T,
  10. class Allocator = ArenaAllocator,
  11. bool isLeaf = false,
  12. template <typename Value> class TComparer = DefaultComparer>
  13. class Stack
  14. {
  15. private:
  16. List<T, Allocator, isLeaf, Js::CopyRemovePolicy, TComparer> list;
  17. public:
  18. Stack(Allocator* alloc) : list(alloc)
  19. {
  20. }
  21. int Count() const { return list.Count(); }
  22. bool Empty() const { return Count() == 0; }
  23. void Clear()
  24. {
  25. list.Clear();
  26. }
  27. bool Contains(const T& item) const
  28. {
  29. return list.Contains(item);
  30. }
  31. const T& Top() const
  32. {
  33. return list.Item(list.Count() - 1);
  34. }
  35. const T& Peek(int stepsBack = 0) const
  36. {
  37. return list.Item(list.Count() - 1 - stepsBack);
  38. }
  39. T Pop()
  40. {
  41. T item = list.Item(list.Count() - 1);
  42. list.RemoveAt(list.Count() - 1);
  43. return item;
  44. }
  45. T Pop(int count)
  46. {
  47. T item = T();
  48. while (count-- > 0)
  49. {
  50. item = Pop();
  51. }
  52. return item;
  53. }
  54. void Push(const T& item)
  55. {
  56. list.Add(item);
  57. }
  58. };
  59. }