I just started studying linked list, and I tried to paint to understand it, and most of it I did, but I tackled with something strange, here's the piece of code I didn't understand:
If the allocation memory failed, what does this code do? and why do I need it? Can't I just free(temp)
and that's it?
while(Head!=NULL)
{
temp=Head;
Head=Head->next;
free(temp);
}
Here's the complete code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct Worker
{
int id;
char name[21];
struct Worker *next;
};
#define NUM 10
void main()
{
int i, id_to_del;
struct Worker *temp, *prev;
struct Worker *Head = NULL;
printf("Enter %d worker details:\n", NUM);
for (i = 0; i < NUM; i++)
{
temp = (struct Worker *)malloc(sizeof(struct Worker));
if (temp == NULL)
{
printf("Error allocating memory for worker #%d!", i + 1);
while (Head != NULL)
{
temp = Head;
Head = Head->next;
free(temp);
}
exit(1);
}
printf("Worker #%d: ", i + 1);
scanf("%d", &temp->id);
gets(temp->name);
temp->next = Head;
Head = temp;
}
}