Filage

Lab5_2

Mar 19th, 2024
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct node {
  6.     node* next;
  7.     int info;
  8. };
  9.  
  10. void createQueue(node*& Begin, node*& End, int n) {
  11.     for (int i = 0; i < n; i++) {
  12.         node* el = new node;
  13.         el->info = rand() % 101 - 50;
  14.         cout << el->info << " ";
  15.         el->next = NULL;
  16.         if (End == nullptr) {
  17.             Begin = End = el;
  18.         }
  19.         else {
  20.             End->next = el;
  21.             End = el;
  22.         }
  23.     }
  24. }
  25.  
  26.  
  27. bool isEmpty(node* Begin) {
  28.     if (Begin == nullptr)
  29.         cout << "Очередь пуста\n";
  30.     return Begin == nullptr;
  31. }
  32.  
  33. void queueList(node* Begin) {
  34.     if (isEmpty(Begin))
  35.         return;
  36.     node* temp = Begin;
  37.     while (temp != nullptr) {
  38.         cout << temp->info << " ";
  39.         temp = temp->next;
  40.     }
  41. }
  42.  
  43. void pop(node*& Begin) {
  44.     if (isEmpty(Begin))
  45.         return;
  46.     node* temp = Begin;
  47.     temp = Begin;
  48.     Begin = Begin->next;
  49.     delete temp;
  50. }
  51.  
  52. int peek(node* Begin) {
  53.     if (isEmpty(Begin))
  54.         return -1;
  55.     return Begin->info;
  56. }
  57.  
  58. int findMax(node* Begin) {
  59.     if (isEmpty(Begin))
  60.         return INT_MIN;
  61.     int maxElement = Begin->info;
  62.     node* temp = Begin->next;
  63.     while (temp != nullptr) {
  64.         if (temp->info > maxElement)
  65.             maxElement = temp->info;
  66.         temp = temp->next;
  67.     }
  68.     return maxElement;
  69. }
  70.  
  71. void moveMaxToFront(node*& Begin) {
  72.     if (isEmpty(Begin))
  73.         return;
  74.     int maxElement = findMax(Begin);
  75.     if (Begin->info == maxElement)
  76.         return;
  77.     node* prevMax = nullptr;
  78.     node* temp = Begin;
  79.     while (temp->info != maxElement) {
  80.         prevMax = temp;
  81.         temp = temp->next;
  82.     }
  83.     prevMax->next = temp->next;
  84.     temp->next = Begin;
  85.     Begin = temp;
  86. }
  87.  
  88.  
  89. int main() {
  90.     srand((unsigned)(time(NULL)));
  91.     setlocale(LC_ALL, "Rus");
  92.     int n;
  93.     node* Begin = nullptr, * End = nullptr;
  94.     cout << "Введите количество узлов: ";
  95.     cin >> n;
  96.     createQueue(Begin, End, n);
  97.     cout << endl << endl;
  98.     queueList(Begin);
  99.     moveMaxToFront(Begin);
  100.     cout << "Очередь после перемещения максимального элемента в начало: ";
  101.     queueList(Begin);
  102.     return 0;
  103. }
  104.  
Advertisement
Add Comment
Please, Sign In to add comment