im finally at the chapter that deals with linked lists. and to me, its confusing. i cant grasp exactly whats going on here. heres the code from the book that im trying to understand...
now, at the additem(int) function it creates a new link, assigns d to the struct member data. what i dont get is what happens after that. *next points to the *first which is set to NULL by theCode:////////////////////////////////////////// struct link //one element of list { int data; //data item link* next; // pointer to the next link }; //////////////////////////////////////////// class linklist //a list of links { private: link* first; //pointer to the first link public: linklist() //no-arg constructor { first = NULL; //no first link } void additem(int d); //add data item (one link) void display(); //display all links }; //------------------------------------------ void linklist::additem(int d) //add item { link* newlink = new link; //make a new link newlink->data = d; //give it data newlink->next = first; //it points to the next link first = newlink; //now first points to this } //------------------------------------------ void linklist::display() //display all links { link* current = first; //set ptr to first link while( current != NULL ) //quit on last link { cout << current->data << endl; //print data current = current->next; //move to next link } } /////////////////////////////////////////////////// int main() { linklist li; //make linked list li.additem(25); //add four items to the list li.additem(36); li.additem(49); li.additem(64); li.display(); //display entire list return 0; }
constructor. then first = newlink? wouldnt just make the newlink point to itself?
upon making the first link li.additem(25), this points to NULL. and first variable is set to point to '25'. and upon adding '36', it points to 25, and then having first point to '36'. LOL did i get this right?