Skip to main content
Engineering LibreTexts

10.4: Looking at the code (continued)

  • Page ID
    34690
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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

    This page titled 10.4: Looking at the code (continued) is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?