fork download
  1. #include <iostream>
  2.  
  3. #ifndef HELLO_WORLD_STACK_H
  4. #define HELLO_WORLD_STACK_H
  5.  
  6. class stack {
  7.  
  8. private:
  9.  
  10. class elem {
  11. public:
  12. const int value;
  13. elem* next;
  14.  
  15. elem(const int, elem*);
  16. };
  17.  
  18. elem* topElem = nullptr;
  19.  
  20. public:
  21. ~stack();
  22. void push(const int);
  23. void pop();
  24. const int top();
  25.  
  26. };
  27.  
  28.  
  29. #endif //HELLO_WORLD_STACK_H+
  30.  
  31.  
  32. stack::elem::elem(const int v, elem* n): value(v), next(n) {}
  33.  
  34. stack::~stack() {
  35. elem* currentElem = topElem;
  36.  
  37. while (currentElem->next != nullptr) {
  38. elem *toDelete = currentElem;
  39. currentElem = currentElem->next;
  40. delete toDelete;
  41. }
  42.  
  43. delete currentElem;
  44. }
  45.  
  46. void stack::push(const int i) {
  47. topElem = new elem(i, topElem);
  48. }
  49.  
  50. void stack::pop() {
  51. if (topElem != nullptr) {
  52. elem* toDelete = topElem;
  53. topElem = topElem->next;
  54. delete toDelete;
  55. } else {throw "empty stack";}
  56. }
  57.  
  58. const int stack::top() {
  59. if (topElem != nullptr) {
  60. return topElem->value;
  61. }
  62. throw "empty stack";
  63. }
  64.  
  65. int main() {
  66.  
  67. auto s = new stack();
  68.  
  69. s->push(1);
  70. s->push(2);
  71. s->push(3);
  72. s->push(4);
  73. s->pop();
  74. s->push(666);
  75.  
  76. std::cout << s->top() << std::endl;
  77.  
  78. delete s;
  79.  
  80. return 0;
  81.  
  82. }
Success #stdin #stdout 0.01s 5264KB
stdin
-v
stdout
666