C++ create linked list and print -


i created linked list , wanted print items.

struct node{     int item;     node *next; }; typedef node* nodeptr;  void insertat(nodeptr headnode, size_t index, int item);  int main(int argc, const char * argv[]) {     nodeptr head;     head = new node;     nodeptr constructor = new node;     head->item = 0;     head->next = constructor;     for(int n = 0; n<8; n++){         constructor->item = n+1;         constructor->next = new node;         constructor = constructor->next;     }     constructor->item = 9;     constructor->next = new node;     constructor->next = nullptr;      for(nodeptr begin = head; begin != nullptr; begin = begin->next){         cout << begin->item << endl;     }      return 0; } 

if write code this, works fine (print 0123456789). after making slight change after loop:

constructor->item = 9; constructor->next = new node; constructor = constructor->next; constructor = nullptr; 

i assumed work same way. output 01234567890 1 more 0 added. can tell me why?

thank help!

you've added new node after 9 entry never defined item value.
value happened default zero.


as difference between

// creates new node... constructor->next = new node;  // ignores making current position end of list constructor->next = nullptr; 

and

// creates new node... constructor->next = new node;  // makes new node current node constructor = constructor->next;  // marks current position end of list // list 1 item longer previous example constructor = nullptr; 

the comments should explain difference.

they both create new node, in second block, constructor = constructor->next; moves new node before marking end of list. end result second block of code has 1 more node in list first block.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -