Sanlover

Untitled

Sep 29th, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct cell
  5. {
  6. int value;
  7. cell* next;
  8.  
  9. cell(int _value, cell* _next)
  10. {
  11. value = _value;
  12. next = _next;
  13. }
  14. };
  15.  
  16. struct queue
  17. {
  18. cell* first;
  19. cell* last;
  20. size_t size;
  21.  
  22. queue()
  23. {
  24. first = last = nullptr;
  25. size = 0;
  26. }
  27.  
  28. bool isEmpty()
  29. {
  30. return first == nullptr;
  31. };
  32. void push(int value)
  33. {
  34. cell* newCell = new cell(value, nullptr);
  35. if (isEmpty())
  36. {
  37. first = last = newCell;
  38. }
  39. else
  40. {
  41. last->next = newCell;
  42. last = newCell;
  43. }
  44. size++;
  45. };
  46. int pop()
  47. {
  48. if (isEmpty())
  49. {
  50. throw exception("Queue is empty");
  51. }
  52. else if (first == last)
  53. {
  54. int toReturn = first->value;
  55. delete first;
  56. first = last = nullptr;
  57. size--;
  58. return toReturn;
  59. }
  60. else
  61. {
  62. int toReturn = first->value;
  63. cell* toDelete = first;
  64.  
  65. first = first->next;
  66. delete toDelete;
  67. size--;
  68. return toReturn;
  69. }
  70. };
  71. void print()
  72. {
  73. if (isEmpty())
  74. {
  75. cout << "Queue is empty" << endl;
  76. return;
  77. }
  78.  
  79. cell* tmp = first;
  80. size_t k = 1;
  81. while (tmp != nullptr)
  82. {
  83. cout << k++ << ") " << tmp->value << endl;
  84. tmp = tmp->next;
  85. }
  86. };
  87. void clear()
  88. {
  89. cell* tmp = first;
  90. while (tmp != nullptr)
  91. {
  92. cell* toDelete = tmp;
  93. tmp = tmp->next;
  94. delete toDelete;
  95. }
  96. first = last = nullptr;
  97. }
  98. int getById(size_t id)
  99. {
  100. if (id > size)
  101. throw exception("Out of size");
  102.  
  103. cell* tmp = first;
  104.  
  105. for (size_t k = 1; k < id; k++)
  106. tmp = tmp->next;
  107.  
  108. return tmp->value;
  109. };
  110. };
  111.  
  112. int main()
  113. {
  114. try
  115. {
  116. queue s;
  117. cout << endl << "1 test" << endl;
  118. s.print();
  119. cout << endl << "2 test" << endl;
  120. s.push(132);
  121. s.push(-32);
  122. s.push(112332);
  123. s.push(1122);
  124. s.print();
  125. cout << endl << "3 test" << endl;
  126.  
  127. size_t amount;
  128. cout << "Enter the amount of elements you want to add: ";
  129. cin >> amount;
  130.  
  131. for (size_t i = 0; i < amount; i++)
  132. {
  133. int value;
  134. cout << "Enter the value of [" << i + 1 << "] element = ";
  135. cin >> value;
  136. s.push(value);
  137. }
  138. s.print();
  139. }
  140. catch (exception ex)
  141. {
  142. cout << "Error: " << ex.what() << endl;
  143. }
  144. return 0;
  145. }
Advertisement
Add Comment
Please, Sign In to add comment