c - 有没有更简单的方法来创建具有给定结构的链表?

标签 c linked-list

<分区>

我尝试用 for 循环来做,但没有成功。这是我当前的实现,它创建了一个包含 6 个元素的链表,但我确信有一种方法可以用循环来完成它,因为我的代码非常乏味。

#include <stdio.h>
#inlcude <stdlib.h>

int main(void) {
    typedef struct _node {
        int data;
        struct _node * next;
    } node_t;

    typedef struct {
        node_t * head;
        node_t * tail;
    } LL_t;

    LL_t* L = malloc(sizeof(LL_t));

    L->head=malloc(sizeof(node_t));
    L->head->data=0;

    L->head->next=malloc(sizeof(node_t));
    L->head->next->data=1;

    L->head->next->next=malloc(sizeof(node_t));
    L->head->next->next->data=2;

    L->head->next->next->next=malloc(sizeof(node_t));
    L->head->next->next->next->data=3;

    L->head->next->next->next->next=malloc(sizeof(node_t));
    L->head->next->next->next->next->data=4;

    L->head->next->next->next->next->next=malloc(sizeof(node_t));
    L->head->next->next->next->next->next->data=5;

    L->head->next->next->next->next->next->next=NULL;
    L->tail=L->head->next->next->next->next->next;

    return 0;
}

我的 for 循环不起作用。

node_t* cur = L->head;
for (int i = 0; i < 6; i++) {
    cur = malloc(sizeof(node_t));
    cur->data = i;
    printf("%d\n", cur->data);
    if (i == 5) {
        cur->next = NULL;
        L->tail = cur;
        break;
    }
    cur = cur->next;
}

最佳答案

此代码将循环并创建您指定的任意多个节点:

int num_nodes = 6;
node_t *L = NULL;
node_t *n;
node_t *tail = NULL;

for (int i = 0; i < num_nodes; i++) {
    n = malloc(sizeof(*n));
    if (n == NULL) {
        exit(1);
    }

    // fill in new node
    n->data = i;
    n->next = NULL;

    // save pointers to the first node we create
    if (L == NULL) {
        // save head pointer
        L = n;

        // save tail pointer
        tail = n;
    } else {
        // link node into list, move tail pointer to newly created node
        tail->next = n;
        tail = n;
    }
}

关于c - 有没有更简单的方法来创建具有给定结构的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49357198/

相关文章:

java - 将链表重新用于另一种类型(通用类型)

java - BJP5练习16.7 : deleteBack — Help me understand the solution

c++ - DLL 中 C 风格函数中的静态变量

c - 如何将 "a pointer to a function with parameters"传递给另一个函数

clang 格式缩进函数参数/参数总是带有 4 个空格

C 文本文件到结构体、数组,然后输出

C、从文件创建单向链表

c - 我如何让 printf 在 w32 上使用 'nan'?

c - 建筑中 undefined symbol ,C

python - 在多路树或连通图中查找一组元素/节点的根元素