Very well, let's take your problem then as stated, a singly linked list with new nodes being appended to the tail (that is we only have a pointer to the head)This is not a school assignment. I am practicing advanced topic linked list in c language. I have already posted the code of a list without function. There are many codes on the internet but I can't understand them. My specific problem is that I'm having trouble writing the function.
Code:
typedef void * Any_ptr;
typedef struct list_struct * List_ptr;
typedef struct node_struct * Node_ptr;
typedef struct list_struct
{
Node_ptr head_ptr;
// other stuff could go here too, like the count of nodes in the list and so on.
} List;
typedef struct node_struct
{
Node_ptr next_ptr;
Any_ptr data_ptr;
} Node;
/* we are now able to simply declare items as "Node" or "List" as well as "Node_ptr" and so on */
List_ptr CreateList()
{
List_ptr ptr = malloc(sizeof(List));
ptr->head_ptr = NULL:
return ptr;
}
void InsertAtTail (List_ptr list_ptr, Any_ptr data_ptr)
{
// Craete a new node and set it up.
Node_ptr node_ptr = malloc(sizeof(Node));
node_ptr->data_ptr = data_ptr;
node_ptr->next_ptr = NULL;
// Case 1. the list is currently empty
if (list_ptr->head_ptr == NULL) // The list is currently empty
{
list_ptr->head_ptr = node_ptr;
return;
}
// Case 2. There is at least one node present
Node_ptr curr_ptr = list_ptr->head_ptr;
while (curr_ptr->next_ptr != NULL)
{
curr_ptr = curr_ptr->next_ptr;
}
// We know that curr_ptr now points to an element with a NULL next_ptr, this is the
// last element, the tail element.
curr_ptr->next_ptr = node_ptr;
return;
}