-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path3-add_node_end.c
50 lines (49 loc) · 1.3 KB
/
3-add_node_end.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "lists.h"
/**
* add_node_end - adds a new node at the end of a list_t list
* @head: double pointer to list_t
* @str: pointer to the first node in list_t
* Return: a poitner to the new node or NULL if it failed
*/
list_t *add_node_end(list_t **head, const char *str)
{
int runner;
list_t *new_end_node;
list_t *firstnode;
new_end_node = malloc(sizeof(list_t));
runner = 0;
if (new_end_node)
{
new_end_node->str = strdup(str);
/* task condition */
if (!new_end_node->str || !str)
{
free(new_end_node);
return (NULL);
}
/* go through str to know the lenght */
/* and assign this to the len variable */
/* and de-reference to new_end_node */
while (new_end_node->str[runner])
runner++;
/* new_end_node will go fordward till is equal to NULL */
new_end_node->next = NULL;
new_end_node->len = runner;
/* this condition is necesary to avoid core dumped */
if (!*head)
{
*head = new_end_node;
return (new_end_node);
}
/* first node will be equal to the pointer to the */
/* first element of the linked list */
firstnode = *head;
/* I go through the linked list */
while (firstnode->next)
firstnode = firstnode->next;
/* first node looks for next node till finds new_end_node */
firstnode->next = new_end_node;
return (new_end_node);
}
return (NULL);
}