创建一个空节点

Creating an empty node

我正在尝试创建一个空节点而不影响指向已连接 list/node 头部的指针。那么,我的代码有什么问题吗?

 CellPtr Create_Node(CellPtr created, int size)
    {
        CellPtr head;
        int i;
        if((created=(CellPtr)malloc(sizeof(Cell)))==NULL)
        {
            printf("Allocation Error");
            exit(1);
        }
        head=created;
        for(i=0; i<size-1; i++)
        {
            if((created->next=(CellPtr)malloc(sizeof(Cell)))==NULL)
            {
            printf("Allocation Error");
            exit(1);
            }
            created=created->next;
        }
        created->next=NULL;

    return head;
    }

问题是您传入 created 但立即覆盖它。不知道为什么要传入created

您似乎正在尝试创建一个包含 size + 1 个空单元格的新链表。我建议将其分成两部分,一部分用于创建空单元格,另一部分用于添加空单元格。

在风格上,指针类型令人困惑。它打破了 * 表示指针的简单视觉约定。让我们摆脱它。

typedef struct _Cell {
    struct _Cell *next;
} Cell;

然后我们有一个函数来创建和初始化一个空单元格。这个DRYs up the code. And don't cast malloc.

Cell *CreateCell() {
    Cell *cell = malloc(sizeof(Cell));
    if( cell == NULL ) {
        fprintf(stderr, "Allocation of Cell failed");
        exit(1);
    }
    cell->next = NULL;

    return cell;
}

然后是一个单独的函数,用于将空单元格添加到现有单元格。我决定 return 新尾巴,因为它看起来很有用。

Cell *AddCells(Cell *tail, size_t num_cells) {
    for(size_t i = 0; i < num_cells; i++) {
        tail->next = CreateCell();
        tail = tail->next;
    }

    return tail;
}

现在我们可以创建一个单元格,添加到它,并在我们需要的时候有效地拥有新的尾巴。

Cell *head = CreateCell();
Cell *tail = AddCells(head, 5);

并且我们可以将单元格添加到任何现有链表的尾部。