Please write in C language! Write a second function that places the new node in
ID: 3572248 • Letter: P
Question
Please write in C language!
Write a second function that places the new node in the tail (i.e., the last node) of the list. It is actually almost the same except we now have to find the last node. We have to do it by starting from the head and employ an auxiliary pointer that moves from node to node. This is best done in a separate function called find_last(head) which is given the head pointer to the list and returns a pointer to the last element of the list.
Here is some guidance.
1) For ease, just write another function called insertnode_tail().
2) Use the same printf() and scanf() to obtain the value of the data member of the new node to be added.
3) Check for NULL pointer as in insertnode_head().
4) Write the find_last(head) function so that it returns a pointer to the last node on the list.
5) Redirect you pointers so that the next pointer of the last node now points to the new node, and the next pointer of the new node points to NULL.
Explanation / Answer
Here is the code for you:
//1) For ease, just write another function called insertnode_tail().
struct node
{
int info;
struct node *next;
};
typedef struct node node;
//4) Write the find_last(head) function so that it returns a pointer to the last node on the list.
node *find_last(node *head)
{
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
while(head->next != NULL)
head = head->next;
return head;
}
void insertnode_tail(node **head, int value)
{
node *tail = find_last(*head);
node *temp = malloc(sizeof(node));
temp->info = value;
temp->next = NULL;
if(tail == NULL)
head = temp;
else
tail->next = temp;
}