Sanlover

Untitled

Sep 29th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. struct cell
  6. {
  7. int value;
  8. cell* next;
  9.  
  10. cell(int value, cell* next)
  11. {
  12. this->value = value;
  13. this->next = next;
  14. }
  15. };
  16.  
  17. struct queue
  18. {
  19. cell* first;
  20. cell* last;
  21.  
  22. queue()
  23. {
  24. first = last = nullptr;
  25. };
  26. bool isEmpty()
  27. {
  28. return first == nullptr;
  29. };
  30.  
  31. void push(int value)
  32. {
  33. cell* newCell = new cell(value, nullptr);
  34. if (isEmpty())
  35. {
  36. first = last = newCell;
  37. }
  38. else
  39. {
  40. last->next = newCell;
  41. last = newCell;
  42. }
  43. };
  44.  
  45. int pop()
  46. {
  47. if (isEmpty())
  48. {
  49. throw exception("queue is empty");
  50. }
  51. else if (first == last)
  52. {
  53. int toReturn = first->value;
  54. delete first;
  55. first = last = nullptr;
  56. return toReturn;
  57. }
  58. else
  59. {
  60. cell* tmp = first;
  61. int toReturn = tmp->value;
  62. first = first->next;
  63. delete tmp;
  64. return toReturn;
  65. }
  66. };
  67.  
  68. void print()
  69. {
  70. if (isEmpty())
  71. {
  72. cout << "Queue is empty" << endl;
  73. return;
  74. }
  75.  
  76. cell* tmp = first;
  77.  
  78. size_t k = 1;
  79. while (tmp != nullptr)
  80. {
  81. cout << k++ << ") " << tmp->value << endl;
  82. tmp = tmp->next;
  83. }
  84. }
  85. };
  86.  
  87. int main()
  88. {
  89. try
  90. {
  91. size_t arraySize;
  92. ifstream in("input.txt");
  93. if (!in.is_open())
  94. throw exception("File is not opened");
  95. in >> arraySize;
  96. int* array = new int[arraySize];
  97.  
  98. size_t k = 0;
  99. while (!in.eof())
  100. in >> array[k++];
  101.  
  102. in.close();
  103.  
  104. queue correctQueue;
  105. for (size_t i = 0; i < arraySize; i++)
  106. if (array[i] > 0)
  107. correctQueue.push(array[i]);
  108. for (size_t i = 0; i < arraySize; i++)
  109. if (array[i] <= 0)
  110. correctQueue.push(array[i]);
  111.  
  112. correctQueue.print();
  113. }
  114. catch (exception ex)
  115. {
  116. cout << "Error: " << ex.what() << endl;
  117. }
  118.  
  119. return 0;
  120. }
Advertisement
Add Comment
Please, Sign In to add comment