我想创建总共三个结构的链接列表。
有什么办法可以让下面的代码变得更简单吗?
#include <stdio.h>
#include <stdlib.h>
struct hello {
int data;
struct hello *next;
};
void main()
{
struct hello *head;
if (head == NULL) {
head = malloc(sizeof(struct hello));
head->next = malloc(sizeof(struct hello));
head->next->next = malloc(sizeof(struct hello));
head->next->next->next = NULL;
}
}
最佳答案
最基本、更容易理解且更简单的解决方案之一是采用指针数组并循环。
我观察到的代码的另一个问题是:
struct hello *head;
if (head == NULL) { }
head
是指针类型的局部变量,除非您的代码这样做,否则不能保证其初始化为零。
在下面的代码中,pNode
将为您执行此操作。
#include <stdio.h>
#include <stdlib.h>
struct hello {
int data;
struct hello *next;
};
int main(void)
{
int i = 0;
struct hello *pNode[3] = { NULL, NULL, NULL };
for(i = 0; i < 3; i++)
{
pNode[i] = malloc(sizeof(struct hello));
if(pNode[i] == NULL)
{
printf("No memory");
// Some error-handling
return -1;
}
}
// lets link all the nodes that were malloc'ed (successfully)
for(i = 0; i < 2; i++) //Note: loop from index 0 to 1, instead of 2.
{
pNode[i]->next = pNode[i+1];
}
pNode[2]->next = NULL;
// Ugly, straight, crude way to write data values
pNode[0]->data = 10;
printf("\n%d", pNode[0]->data);
pNode[0]->next->data = 20;
printf("\n%d, %d", pNode[0]->next->data, pNode[1]->data);
pNode[0]->next->next->data = 30;
printf("\n%d, %d", pNode[0]->next->next->data, pNode[2]->data);
return 0;
}
确保您养成检查 malloc 是否返回任何内容的习惯,否则您还需要处理该错误。
请记住,上面的代码始终可以以更加优化、智能和复杂的方式实现。只是我想提出一个基本代码,它似乎按照它所说的那样做,并且您可以随时在需要时进行更改。
关于c - 创建三个结构体链表的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922709/