Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Adding to the Queue

Listing 3 shows the implementation of the code used to add elements to the end of the queue. Three cases exist:

  • Adding to an empty queue
  • Adding to a queue containing just one item
  • Adding to a queue containing multiple items

The code in Listing 3 handles all three cases.

Listing 3 Adding to the Queue

void NMSServiceQueue::add(QueueElementPtr serviceRequest)
  if (queueIsEmpty())
    startOfQueue = serviceRequest;
    startOfQueue->nextQueueElement = NULL;
    endOfQueue = startOfQueue;
    endOfQueue->nextQueueElement = NULL;
    // Handle a single entry queue
    if (startOfQueue == endOfQueue)
      startOfQueue->nextQueueElement = serviceRequest;
    // Add the new element to the end of the queue
    endOfQueue->nextQueueElement = serviceRequest;
    endOfQueue = serviceRequest;

The only real complexity of Listing 3 is the updating of the two variables startOfQueue and endOfQueue. Memory allocation occurs before this method is called, and deallocation also occurs outside this method, which helps keep the queue class more simple.

  • + Share This
  • 🔖 Save To Your Account