Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. template <typename T>
  2. class Stack {
  3. public:
  4. struct Node {
  5. T data;
  6. Node *next = nullptr;
  7. Node(T data) : data(data) {}
  8. Node(T data, Node *next) : data(data), next(next) {}
  9. };
  10. Node *top;
  11. int size_;
  12.  
  13. Stack() : size_(0), top(nullptr) {}
  14.  
  15. bool empty() {
  16. return top == 0;
  17. }
  18.  
  19. void push(T data) {
  20. if(empty()) {
  21. top = new Node(data);
  22. size_++;
  23. } else {
  24. top = new Node(data, top);
  25. size_++;
  26. }
  27. }
  28.  
  29. T pop() {
  30. if(!empty()) {
  31. T ret = top->data;
  32. Node *tmp = top->next;
  33. delete top;
  34. top = tmp;
  35. size_--;
  36. return ret;
  37. }
  38.  
  39. return -1;
  40. }
  41.  
  42. int size() {
  43. return size_;
  44. }
  45.  
  46. ~Stack() {
  47. if(empty()) return;
  48.  
  49. if(size_ == 1) {
  50. delete top;
  51. return;
  52. }
  53.  
  54. Node *current = top;
  55. Node *next;
  56. while( current != 0 ) {
  57. next = current->next;
  58. delete current;
  59. current = next;
  60. }
  61. top = nullptr;
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement