Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

9. Define countNodes member function of the SLList class as declared in the Figu

ID: 3698701 • Letter: 9

Question

9. Define countNodes member function of the SLList class as declared in the Figure - 3. The function returns the number of nodes in the list 10.Define printlist member function of the SLList class as declared in the Figure - 3. The function prints the value/data stored in the list nodes in one row with a tab space in- between . Pre-condition the list should not be empty. 11.Define insertToHead member function of the SLList class as declared in the Figure 3 The function inserts a new node with the given value at the front/head end of the list. . Pre-condition None . Post-condition The new node is inserted at the front/head end of the list. 12.Define insertToTail member function of the SLList class as declared in the Figure - 3 The function inserts a new node with the given value at the rear/tail end of the list. . Pre-condition - None. . Post-condition The new node is inserted at the rear/tail end of the list.

Explanation / Answer

int countNodes()

{

    int count = 0;

   

    // point trav to head of list

    Node *trav = head;

   

    // loop until the list is empty

    while(trav)

    {

        count++;

       

        // move to next node

        // getNext() return pointer to next node

        trav = trav->getNext();

    }

   

    return count;

}

void printList()

{

    // point trav to head of list

    Node *trav = head;

   

    // loop until the list is empty

    while(trav)

    {

        // getData() return the value of current node

        cout<<trav->getData()<<" ";

       

        // move to next node

        // getNext() return pointer to next node

        trav = trav->getNext();

    }

}

void insertToHead(int value)

{

    // create a new node

    Node *new_node = new Node(value);

    // make new node point to current head

    new_node->setNext( head );

   

    // make new_node the new head of the list

    head = new_node;

   

    // if the list has only 1 node

    if( head->getNext() == NULL )

        tail = new_node;

}

void insertToTail(int value)

{

    // create a new node

    Node *new_node = new Node(value);

   

    // if the list is empty

    if( tail == NULL )

    {

        // make new_node the new head of the list

        head = new_node;

       

        // make new_node the new tail of the list

        tail = new_node;

    }

    else

    {

        tail->setNext( new_node );

       

        // make new_node the new tail of the list

        tail = new_node;

    }

}