Advertisement
ivorakitin

Queue

Apr 9th, 2025 (edited)
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. //дефиниране и инициализация на опашка
  5. struct elem
  6. {
  7.     int key;
  8.     elem *next;
  9. } *first = NULL, *last = NULL, *p;
  10.  
  11. void push(int n);   //prototype
  12. int pop(int &n);    //prototype
  13. void push(elem *&f, elem *&l, int n);   //prototype
  14. int pop(elem *&f, elem *&l, int &n);    //prototype
  15.  
  16.  
  17.  
  18. void push(int n)        //добавяне на елемент
  19. {
  20.     p = last;
  21.     last = new elem;
  22.     last->key = n;
  23.     last->next = NULL;
  24.     if(p != NULL)
  25.         p->next = last;
  26.     if (first == NULL)  //добавяне на първи елемент
  27.     {
  28.         first = last;
  29.     }
  30. }
  31.  
  32. int pop(int &n)     //извличане на елемент
  33. {
  34.     if (first)      //проверка за непразна опашка
  35.     {
  36.         n = first->key;
  37.         p = first;
  38.         first = first->next;
  39.         if (first == NULL)
  40.             last = first;
  41.         delete p;       //премахване на елемента
  42.         return 1;
  43.     }
  44.     else
  45.         return 0;       //опашката е празна
  46. }
  47.  
  48. void push(elem *&f, elem *&l, int n)        //добавяне на елемент
  49. {
  50.     elem *p = l;
  51.     l = new elem;
  52.     l->key = n;
  53.     l->next = NULL;
  54.     if(p != NULL)
  55.         p->next = l;
  56.     if (f == NULL)  //добавяне на първи елемент
  57.     {
  58.         f = l;
  59.     }
  60. }
  61.  
  62. int pop(elem *&f, elem *&l, int &n)     //извличане на елемент
  63. {
  64.     elem *p;
  65.     if (f)      //проверка за непразна опашка
  66.     {
  67.         n = f->key;
  68.         p = f;
  69.         f = f->next;
  70.         if (f == NULL)
  71.             l = f;
  72.         delete p;       //премахване на елемента
  73.         return 1;
  74.     }
  75.     else
  76.         return 0;       //опашката е празна
  77. }
  78.  
  79.  
  80.  
  81. int main()
  82. {
  83.     int num;
  84.     cout<<"Input integers:\n";  
  85.     while (cin >> num)
  86.         push(num);
  87.     cout<<"\nBuffered data:  ";
  88.     while (pop(num))
  89.     {
  90.         cout << num << "  ";
  91.     }
  92.     cout << "\n";
  93.     return 0;
  94. }
  95.  
Tags: QUEUE
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement