Creating a linked list with a for loop

雨燕双飞 提交于 2019-12-02 17:28:33

问题


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


回答1:


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




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!