smatskevich

QueueOnList

Oct 24th, 2020
573
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <assert.h>
  2. #include <iostream>
  3.  
  4. struct Node {
  5.   int data;
  6.   Node* next;
  7.  
  8.   Node(int value) : data(value), next(nullptr) {}
  9. };
  10.  
  11. // Очередь целых чисел.
  12. class Queue {
  13.  public:
  14.   Queue(int size) : head(nullptr), tail(nullptr) {}
  15.   ~Queue() {
  16.     for (Node* c = tail; c != nullptr;) {
  17.       Node* next = c->next;
  18.       delete c;
  19.       c = next;
  20.     }
  21.   }
  22.  
  23.   // Добавление и извлечение элемента из очереди.
  24.   void enqueue(int a) {
  25.     if (tail == nullptr) {
  26.       tail = head = new Node(a);
  27.     } else {
  28.       head->next = new Node(a);
  29.       head = head->next;
  30.     }
  31.   }
  32.  
  33.   int dequeue() {
  34.     assert(tail != 0);
  35.     Node* next = tail->next;
  36.     delete tail;
  37.     tail = next;
  38.     if (tail == nullptr) head = nullptr;
  39.   }
  40.  
  41.   // Проверка на пустоту.
  42.   bool empty() const { return tail == nullptr; }
  43.  
  44.  private:
  45.   Node* head;
  46.   Node* tail;
  47. };
  48.  
RAW Paste Data