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; }
5 Respuestas
+ 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.
+ 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.
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;
0
Mark McGuire
Thanks alot for your explanation. 🙏🏻🙏🏻
0
Welcome.