Tvor0zhok

Класс очередь

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