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