Advertisement
Tvor0zhok

Класс стек

Mar 31st, 2021 (edited)
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. //main.cpp
  2. #include <iostream>
  3. #include <string>
  4. #include "stack.cpp"
  5. using namespace std;
  6.  
  7. void reverse (stack <string> &st)
  8. {
  9. if (st.empty()) return;
  10. else
  11. {
  12. string word = st.top();
  13. st.pop();
  14.  
  15. reverse(st);
  16.  
  17. st.push_front(word);
  18. }
  19. }
  20.  
  21. void print (stack <string> st)
  22. {
  23. while(!st.empty())
  24. {
  25. cout << st.top() << " ";
  26. st.pop();
  27. }
  28.  
  29. cout << '\n';
  30. }
  31.  
  32. int main()
  33. {
  34. stack <string> st;
  35.  
  36. cout << "Введите ваши слова: ";
  37.  
  38. string word;
  39. while (cin >> word) st.push_back(word);
  40. //останавливаем цикл зажав Ctrl + Z или Ctrl + D
  41.  
  42. reverse(st);
  43. print(st);
  44. return 0;
  45. }
  46.  
  47. //stack.cpp
  48. #include <cassert>
  49.  
  50. template <class Type>
  51. class stack
  52. {
  53. struct element
  54. {
  55. Type inf;
  56. element *next;
  57. element (Type i, element *n) : inf(i), next(n) {}
  58. };
  59.  
  60. element *head;
  61.  
  62. public:
  63.  
  64. stack() : head(nullptr) {}
  65.  
  66. bool empty() { return head == nullptr; }
  67.  
  68. void push_back (Type x) { head = new element (x, head); }
  69.  
  70. Type top() { assert(!empty()); return head -> inf; }
  71.  
  72. void pop()
  73. {
  74. if (empty()) return;
  75. else
  76. {
  77. element *st = head;
  78. head = st -> next;
  79. delete st;
  80. }
  81. }
  82.  
  83. void push_front (Type x)
  84. {
  85. if(empty()) push_back(x);
  86. else
  87. {
  88. Type y = top();
  89. pop();
  90.  
  91. push_front(x);
  92.  
  93. push_back(y);
  94. }
  95. }
  96. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement