-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-add_node_end.c
56 lines (50 loc) · 915 Bytes
/
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
51
52
53
54
55
56
#include "lists.h"
#include <string.h>
#include <stdlib.h>
/**
* add_node_end - Adds a new node at the end of a list_t list
* @head: A pointer pointing to a pointer to the first node.
* @str: The string variable to be stored in the newNode
*
* Return: On success -> Te address of the new element
* On fail -> NULL
*/
list_t *add_node_end(list_t **head, const char *str)
{
int len;
char *newStr;
list_t *newNode;
list_t *lastNode;
newNode = malloc(sizeof(list_t));
if (newNode == NULL)
{
return (NULL);
}
newStr = strdup(str);
if (newStr == NULL)
{
free(newNode);
return (NULL);
}
for (len = 0; str[len];)
{
len++;
}
newNode->str = newStr;
newNode->len = len;
newNode->next = NULL;
if (*head != NULL)
{
lastNode = *head;
while (lastNode->next != NULL)
{
lastNode = lastNode->next;
}
lastNode->next = newNode;
}
else
{
*head = newNode;
}
return (*head);
}