I am trying to create an empty node without affecting the pointer which points on the head of the connected list/node. So, is there is any problem in my code?
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;
}
A problem is you're passing in created
but immediately overwriting it. I don't know why created
is passed in.
It seems you're trying to make a new linked list with size
+ 1 empty cells. I would suggest splitting this into two pieces, one to create an empty cell, and one to add empty cells.
Stylistically, pointer types are confusing. It breaks the simple visual convention that *
means pointer. Let's get rid of that.
typedef struct _Cell {
struct _Cell *next;
} Cell;
Then we have one function to make and initialize an empty cell. This 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;
}
Then a separate function to add empty cells to an existing cell. I've decided to return the new tail because that seems useful.
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;
}
Now we can create a cell, add to it, and efficiently have the new tail should we need it.
Cell *head = CreateCell();
Cell *tail = AddCells(head, 5);
And we can add cells to the tail of any existing linked list.