C++ - OOP implementation of linked list, I not sure why adding to end is not working for me, please advise -


i refreshing knowledge of c++ oop not sure why can traversal , adding end of list , running. advice on context highly appreciated.

    #include "stdafx.h"     #include "linkedlist.h"       linkedlist::linkedlist(void)     {     }       linkedlist::~linkedlist(void)     {     }          void linkedlist::add(node* node)            {                node* root = this->getroot();                if(root !=null)                     { //with 2 nodes commented code worked                          //while(root->getnextnode() != null){}                         //root->setnextnode(node); //this part culprit                         node* newnode = root->getnextnode();                         while(newnode!=null)                         {                             newnode = newnode->getnextnode();                         } //i thinking reaching last node using traversal                         newnode = new node(node->getdata(),node->getnextnode());                     }else                     {                         this->setroot(node);                     }             };      void linkedlist::traversenodes()         {             node* node = this->getroot();             printf("\ntraversing nodes:");             while(node != null){                 printf("%d", node->getdata());                 node = node->getnextnode();             }         } 

the problem code once set pointer newnode null, pointing new node won't change previous last node.

try this:

node* root = this->getroot(); if (root != null) {     node* parent = root;     while(true) {         // 2 variables mean have access previous node,         // needed add next one.         node* child = parent->getnextnode();         if (child != null) {             parent = child;         } else {             parent->setnextnode(/* new node */);             break; // edit         }     } } else //... 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -