fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. class Stack
  6. {
  7. struct Unit
  8. {
  9. Unit *prev;
  10. T value;
  11. Unit(T value);
  12. };
  13. public:
  14. Stack();
  15. void Push(T value);
  16. int Count();
  17. T Top();
  18. T Pop();
  19. ~Stack();
  20. private:
  21. unsigned int count;
  22. Unit *top;
  23.  
  24. };
  25.  
  26. template<typename T>
  27. Stack<T>::Unit::Unit(T value)
  28. {
  29. this->value = value;
  30. prev = nullptr;
  31. }
  32.  
  33. template<typename T>
  34. Stack<T>::Stack()
  35. {
  36. top = nullptr;
  37. count = 0;
  38.  
  39. std::cout << "The size of each unit is " << sizeof(Unit) << " bytes." << std::endl;
  40. }
  41.  
  42. template<typename T>
  43. void Stack<T>::Push(T value)
  44. {
  45. if (top == nullptr)
  46. {
  47. top = new Unit(value);
  48. }
  49. else
  50. {
  51. Unit *tmp = new Unit(value);
  52. tmp->prev = top;
  53. top = tmp;
  54. }
  55. count++;
  56. }
  57.  
  58. template<typename T>
  59. T Stack<T>::Pop()
  60. {
  61. T value = top->value;
  62. Unit *tmp = top->prev;
  63. delete top;
  64. top = tmp;
  65. count--;
  66. return value;
  67. }
  68.  
  69. template<typename T>
  70. Stack<T>::~Stack()
  71. {
  72. Unit *curr = top;
  73. if (!curr)
  74. {
  75. return;
  76. }
  77. while (curr)
  78. {
  79. Unit* tmp = curr->prev;
  80. delete curr;
  81. curr = tmp;
  82. }
  83. }
  84.  
  85.  
  86. int main() {
  87. // your code goes here
  88.  
  89. Stack<int> myStack;
  90.  
  91.  
  92. return 0;
  93. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
The size of each unit is 16 bytes.