I'm learning C and I'm trying to understand a better concept of a Linked List. I have a code as an example (I changed it to be like the one i want to understand better). The code doesnt have any mistakes but again like i said it's to understand it better. Please have a look at the code first and below the code i'll ask my questions:
Here is the code for my struct and my first function:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct client{
char first_name[20];
char last_name[20];
char id;
char reference;
char deposit;
struct client *next; // pointer to the next entry in the clients list
};
typedef struct client new_Client;
/***********************************************************
* find_Client
* Finds a place in the list to insert new user
* Input: User's first and last name, id, reference, deposit
* Returns: A pointer to teh struct which AFTER we'll insert
the new struct. NULL if head of the linked-list
***********************************************************/
new_Client *find_Client(char *new_last_name, new_Client *head)
{
new_Client *prev = NULL; // previous has nothing
new_Client *curr = head; // current is the head
while (curr != NULL) //// while the current is not NULL because if it's null it's not head
{
if (strcmp(new_last_name, curr->last_name)<0)
break;
prev = curr;
curr = curr->next; // pointing to the next node
}
return prev;
}
And here is my next function where i usually have a problem understanding
/***********************************************************
* add_new_Client
* Adds a new client
* Input: clients details and the address of the list's head
* Returns: nothing
***********************************************************/
void add_new_Client(char *first_n, char *last_n, char *ident, char *ref, char *dep, new_Client **head)
{
new_Client *after;
// create new entry
new_Client *new_entry = (new_Client*)malloc(sizeof(new_Client)); //allocating size of the struct
if (NULL == new_entry)
{
exit(1); //Q1: does it mean that it terminates?
}
else
{
strcpy(new_entry->first_name, first_n);
strcpy(new_entry->last_name, last_n);
strcpy(&new_entry->id, ident);
strcpy(&new_entry->reference, ref);
strcpy(&new_entry->deposit, dep);
}
after = find_Client(new_entry->last_name, *head); // Q2: don't understand this line..
if (NULL == after) // new head
{
if (NULL == *head) // Q3: for adding the first item (when the head is NULL) --> why is this condition necessary
{
new_entry->next = NULL;
}
else
{
new_entry->next = *head;
}
*head = new_entry;
}else
{ //add in the middle
new_entry->next = after->next;
after->next = new_entry;
}
}
Okay so i put my questions in the code itself. They're marked as Q1,Q2 and Q3. Please let me know if you would prefer i edit on my post and change the questioning methode for it to be easier for you to understand my questions.