Here is my struct
struct ListItem{
int data;
struct ListItem *next;
};
Assuming the first node of the linked list will have data = 0, I want to write a for loop that creates a linked list of size 5 but I'm not sure how to work
I tried the following
int main(int argc, char* argv[]){
struct ListItem a;
a.data = 0;
for (int i = 1; i < 5; i++){
struct ListItem *pointer = &a;
struct ListItem nextnode;
nextnode.data = i;
a.next = &nextnode;
pointer = pointer->next;
}
}
But the result is a.data = 0 and a.next->data = 4
Don't modify a. Take a temp node starting as a. Make it's next point to the new node and then set temp node to the new node. Also allocate dynamically in heap. Otherwise the memory will get deallocated after every loop run
struct ListItem a[5] = { {0, NULL}};
struct ListItem *pointer = &a[0];
for (int i = 0; i < 5; i++){
a[i].data = i;
if(i != 5 -1)
a[i].next = &a[i+1];
}
来源:https://stackoverflow.com/questions/21661993/creating-a-linked-list-with-a-for-loop