c - 创建三个结构体链表的简单方法

标签 c struct

我想创建总共三个结构的链接列表。
有什么办法可以让下面的代码变得更简单吗?

#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/

相关文章:

c - SDL 音频回拨不起作用?

c++ - C++ 对象成员数组的默认初始化?

c - 如何访问结构内部的 union ?

c - 如何在C编程中使用多个动态分配?

c - 我怎样才能让 Module::Build 编译和链接我的小 C 程序?

c - c中的字节操作

c - 在C中, '=='是否曾用于变量赋值?

objective-c - 为什么 {} 适用于 C 结构而不适用于属性

struct - 如何在强制使用 "new"构造函数的同时使结构的所有字段公开可读

c - 指向嵌套结构中的结构的指针