使用 for 循环创建链表 [英] Creating a linked list with a for loop
本文介绍了使用 for 循环创建链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的结构
struct ListItem{
int data;
struct ListItem *next;
};
假设链表的第一个节点的数据为 0,我想编写一个 for 循环来创建一个大小为 5 的链表,但我不知道如何工作
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
我尝试了以下
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;
}
}
但结果是a.数据 = 0和 a.next->data = 4
But the result is a.data = 0 and a.next->data = 4
推荐答案
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];
}
这篇关于使用 for 循环创建链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文