Skip to main content
Engineering LibreTexts

10.4: Looking at the code (continued)

  • Page ID
    34690
  • To insert an item into the queue it is very similar to the linked list and the stack. This is the advantage of learning how to manage linked lists, they can be used in many other types of data structures.

    void qInsert(int inVal) 
    { 
       // Create a new LL node 
       QNode* temp = new QNode();   
       temp->data = inVal;
       temp->next = NULL;
    
       // If rear is NULL then we have a new 
       // empty queue  and this 
       // new node is both front and rear 
       if (rear == NULL) { 
          front = rear = temp; 
          return; 
       } 
    
       // Add the new node at 
       // the end of queue and change rear 
       rear->next = temp; 
       rear = temp; 
    
     }
    The first thing we need to do is allocate memory - which is done with the new QNode() code. Then the value that is passed as an argument to the qInsert() function is assigned the the temp node, and we set the next pointer to NULL, 
    If rear (and head) are NULL, we know that this is a new queue, and so we simply set both the front and the rear to the newly created temp value.
    OTHERWISE
    we simply have to adjust the current rear->next pointer to point at the temp value, and make rear point at this new item as the new rear.
     
    Adapted from:
    "Queue – Linked List Implementation" by Gaurav Kumar is licensed under CC BY-SA 4.0
    • Was this article helpful?