c++ - understanding how to add new node at end of link list -
struct node { int data; node *next; }; //function add node . . . listnode <nodetype> *newptr = getnewnode(value); if( isempty() ) //function check if list empty firstptr = lastptr = newptr; else { lastptr->next = newptr; // 1 do? lastptr = newptr; // 2 , this? } this piece of code textbook. im having hard time understanding 2 lines marked numbers above. understand if list empty point first , last pointer our newly created node. however, if there node in list, how work?
the thing confused me both lines pointed newptr created. difference between line marked 1 , 2?
here take on it.
for 1: telling pointer part of lastptr point new node
for 2: point lastptr newptr? why did point newptr twice?
can please explain?
lastptr->next = newptr; // 1 do
at stage, lastptr points node @ end of list. next member null, because nothing follows after yet. next updated point @ new node because new node follows after previous node, previous node has updated point @ next node in list - new node being inserted.
lastptr = newptr; // 2 , this?
this telling list new node last node in list.
Comments
Post a Comment