Creating linked list in c++ | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Creating linked list in c++

I separately create each note and linked team together but i want to linked them using a loop. I don't know whether the code using a loop is ok or not ? struct node { int data; struct *next; } // h is for head and t is for temporary struct *h, *t, *n; n=new node; n->data=1; t=n; h=n; n=new node; n->data=2; t->next=n; t=n; n=new node; n->data=3; t->next=n; t=n; n=new node; n->data=4; t->next=n; n->next =NULL; And this is the same code using loop , is it correct??? struct node { int data; struct node *next; } // h is for head and t is for temporary struct *h, *t, *n; n=new node; n->data=1; n->next =NULL; t=n; h=n; for(int i=0;i<5;i++) { n=new node; cin >>n->data; n->next =NULL; t->next=n; t=n; }

11th May 2020, 5:59 PM
Armina
Armina - avatar
5 Respostas
+ 1
I recently did this. Why is next a struct*? Shouldn't it be a node*? Other than that it probably depends on how you want to put in the data. If I were to do a given z nodes I'd do something like For(int i=0; i <=z; i++){ If (i==z){n->next=nullptr} Else{ n=new node; n->data=i;//or whatever you need in there t->next=n; t=n; }} Or something similar.
11th May 2020, 7:57 PM
Mark McGuire
Mark McGuire - avatar
+ 1
Armina the last node must be null otherwise it's initialized to whatever is in that register. It could be null, or it could be 42, apple, dghgnskfihsb, anything. We want 0000 because we can't walk the list later and end properly. We can't say If (n->next==junk) Because there is no junk in the computer (hopefully. ) it's all good data, but some of it is no longer used. It's like a shopping list where you keep writing on the same paper with pencil . Is "watermelon" junk? No. But if you already got it you can erase it and not clutter your new list. Now that I look back I'd set all the last nodes in a list to null. Then reset them later. In case something unexpected happens.
11th May 2020, 8:12 PM
Mark McGuire
Mark McGuire - avatar
0
Mark McGuire yes you're right, next is node pointer, i just forgot to write it. Thanks for your answer. Is writing n->next =NULL; necessary it this code? Why do we wright it? n=new node; cin>>n->data; n->next =NULL; t->next=n; t=n;
11th May 2020, 8:04 PM
Armina
Armina - avatar
0
Mark McGuire Thanks alot for your explanation. šŸ™šŸ»šŸ™šŸ»
11th May 2020, 8:16 PM
Armina
Armina - avatar
0
Welcome.
11th May 2020, 8:17 PM
Mark McGuire
Mark McGuire - avatar