Source for enqueue() and dequeue() functions to add and remove data from a queue in a class.

Node Struct Definition

1
2
3
4
5
struct node {
     string what; // Used for brand
     string serialNumber;
     node* next; // For accessing next node in queue
};

Class Definition File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class car {
     public:
          // Class constructor
          car() {
               size = 0;
               front = NULL;
               rear = NULL;
          }

          // Add a node to the queue
          void enqueue(string brand, string serial);
          void dequeue(string& brand, string& serial);
     private:
          // Queue size
          int size;

          // Queue front and rear
          node* front;
          node* rear;
};

The data that’s stored in each node of our queue are the two string variables, brand and serial. The beginning of the queue is front while the end of it is rear.

enqueue() Function

1
2
3
4
5
6
7
8
9
10
11
12
13
void car::enqueue(string brand, string serial) {
     node* ptr = new node;
     ptr->what = brand;
     ptr->serialNumber = serial;
     ptr->next = NULL;

     if (!rear)
          front = ptr;
     else
          rear->next = ptr;
     rear = ptr;
     size++;
}

dequeue() Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void car::dequeue(string& brand, string& serial) {
     node* tmpPtr = front;

     brand = front->what;
     serial = front->serialNumber;

     front = front->next;

     if (!front)
          rear = NULL;

     size = size - 1;

     delete tmpPtr;
}

The brand and serial data variables are passed by reference so that they can be stuffed with the values that are removed from the queue, just in case you need them again elsewhere.