-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.c
126 lines (96 loc) · 2.25 KB
/
list.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include "list.h"
/**
* str_to_list - turn a string into a linked list
* @str: string passed
* @delim: delimiter passed
* Return: pointer to list
*/
list_t *str_to_list(const char *str, char delim)
{
list_t *head = NULL;
if (!str)
return (NULL);
if (!_str_to_list(&head, str, delim))
free_list(&head);
return (head);
}
/**
* _str_to_list - turn a string into a linked list (helper)
* @tailptr: pointer to the tail of the list
* @str: string
* @delim: delimiter
*
* Return: pointer to the tail of the list
*/
list_t *_str_to_list(list_t **tailptr, const char *str, char delim)
{
list_t *tail;
ssize_t len = _strchr(str, delim);
if (len == -1)
len = _strlen(str);
tail = add_node_end(tailptr, NULL);
if (!tail)
return (NULL);
tail->str = _memdup(str, len + 1);
if (!tail->str)
return (NULL);
tail->str[len] = '\0';
if (str[len])
return (_str_to_list(&tail, str + len + 1, delim));
return (tail);
}
/**
* add_node - insert a string at the beginning of the list
* @headptr: a pointer to the address of the first list node
* @str: the string to add to the list
* Return: If memory allocation fails, return NULL. Otherwise, return the
* address of the new no
*/
list_t *add_node(list_t **headptr, const char *str)
{
list_t *new;
if (!headptr)
return (NULL);
new = malloc(sizeof(list_t));
if (!new)
return (NULL);
new->str = _strdup(str);
new->next = *headptr;
*headptr = new;
return (new);
}
/**
* add_node_end - add a string at the end of the list
* @headptr: a pointer to the address of the first list node
* @str: the string to add to the list
* Return: If memory allocation fails, return NULL. Otherwise, return the
* address of the new no
*/
list_t *add_node_end(list_t **headptr, const char *str)
{
list_t *new;
if (!headptr)
return (NULL);
if (*headptr)
return (add_node_end(&((*headptr)->next), str));
new = malloc(sizeof(list_t));
if (!new)
return (NULL);
new->str = _strdup(str);
new->next = *headptr;
*headptr = new;
return (new);
}
/**
* free_list - free a linked list and and set head to NULL
* @headptr: the first list node
*/
void free_list(list_t **headptr)
{
if (!*headptr)
return;
free_list(&((*headptr)->next));
free((*headptr)->str);
free(*headptr);
*headptr = NULL;
}