我正在尝试创建一个空节点,而不会影响指向所连接列表/节点头上的指针。所以,我的代码有问题吗?
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;
}
似乎您正在尝试使用size
+ 1个空单元格创建一个新的链表。我建议将其分成两部分,一个创建一个空单元,另一个添加空单元。
一个问题是您要传入created
,但立即将其覆盖。您正在尝试使用双指针执行某些操作,或者那是不必要的。
通常,指针类型令人困惑。它打破了*
表示指针的简单视觉约定。让我们摆脱它。
typedef struct _Cell {
struct _Cell *next;
} Cell;
然后,我们有一个函数来创建和初始化一个空单元格。这个DRYs up the code。和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;
}
然后是一个单独的功能,可以将空单元格添加到现有单元格中。我决定退回新的尾巴,因为这似乎很有用。
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 *cell = CreateCell();
Cell *tail = AddCells(cell, 5);