Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. ///STACK///
  2. #include <iostream>
  3. #include <stdexcept>
  4. using namespace std;
  5.  
  6. struct Node {
  7. int data;
  8. Node* previous = nullptr;
  9.  
  10. Node(int data, Node* previous = nullptr) {
  11. this->data = data;
  12. this->previous = previous;
  13. }
  14. };
  15.  
  16. class Stack {
  17. private:
  18. Node* top = nullptr;
  19. public:
  20. Stack() { }
  21.  
  22. void _copyStackRecursive(Node* current) {
  23. if (current != nullptr) {
  24. _copyStackRecursive(current->previous);
  25. push(current->data);
  26. }
  27. }
  28.  
  29. void copyStack(const Stack& rhs) {
  30. _copyStackRecursive(rhs.top);
  31. }
  32.  
  33. void freeMemory() {
  34. while(top != nullptr) {
  35. Node* previous = top->previous;
  36. delete top;
  37. top = previous;
  38. }
  39. }
  40.  
  41. Stack(const Stack& rhs) {
  42. copyStack(rhs);
  43. }
  44.  
  45. Stack& operator=(const Stack& rhs) {
  46. if (this != &rhs) {
  47. freeMemory();
  48. copyStack(rhs);
  49. }
  50. return *this;
  51. }
  52.  
  53. ~Stack() {
  54. freeMemory();
  55. }
  56.  
  57. void push(int number) {
  58. if (isEmpty()) {
  59. top = new Node(number);
  60. } else {
  61. Node* newTop = new Node(number, top);
  62. top = newTop;
  63. }
  64. }
  65.  
  66. void pop() {
  67. if (!isEmpty()) {
  68. Node* oldTop = top;
  69. top = top->previous;
  70. delete oldTop;
  71. } else {
  72. throw std::underflow_error("Stack is empty");
  73. }
  74. }
  75.  
  76. int peek() const {
  77. if (!isEmpty()) {
  78. return top->data;
  79. } else {
  80. throw std::underflow_error("Stack is empty");
  81. }
  82. }
  83.  
  84. bool isEmpty() const {
  85. return top == nullptr;
  86. }
  87. };
  88.  
  89. int main() {
  90. Stack s;
  91. s.push(1);
  92. s.push(2);
  93. s.push(3);
  94.  
  95. Stack d(s);
  96. while (!d.isEmpty()) {
  97. cout << d.peek();
  98. d.pop();
  99. }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement