enqueue and dequeue

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

Node Struct Definition

C++

struct node {
     string what; // Used for brand
     string serialNumber;
     node* next; // For accessing next node in queue
};

Class Definition File

C++

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

C++

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

C++

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.

This entry was posted in Programming and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. grouch
    Posted 16 November 2005 at 4:10 AM | Permalink

    bash 0\/\/nz j00!

  2. Josh Priestley
    Posted 28 December 2005 at 3:31 PM | Permalink

    Oh no! Here comes the queue monster!

    “#include “

  3. Josh Priestley
    Posted 28 December 2005 at 3:43 PM | Permalink

    Sarah! Your comment section hates lt and gt characters!

    include<queue>

  4. nicco
    Posted 14 May 2010 at 8:44 AM | Permalink

    how to make a program with array and implement dequeue and enqueue funtions

One Trackback

  1. [...] Random blog to the rescue!  Thank you Three Till Seven! [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>