-
Notifications
You must be signed in to change notification settings - Fork 3
/
list2.c
125 lines (113 loc) · 2.06 KB
/
list2.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
#include "shell.h"
/**
* list_len - function that determines length of linked list
* @h: pointer to first node
*
* Return: size of list
*/
size_t list_len(const list_t *h)
{
size_t t = 0;
while (h)
{
h = h->next;
t++;
}
return (t);
}
/**
* list_to_strings - function that returns an array
* of strings of the list->str
* @head: address of pointer to first node
*
* Return: array of strings
*/
char **list_to_strings(list_t *head)
{
list_t *node = head;
size_t x = list_len(head), y;
char **strs;
char *str;
if (!head || !x)
return (NULL);
strs = malloc(sizeof(char *) * (x + 1));
if (!strs)
return (NULL);
for (x = 0; node; node = node->next, x++)
{
str = malloc(_strlen(node->str) + 1);
if (!str)
{
for (y = 0; y < x; y++)
free(strs[y]);
free(strs);
return (NULL);
}
str = _strcpy(str, node->str);
strs[x] = str;
}
strs[x] = NULL;
return (strs);
}
/**
* print_list - function that prints all elements
* of a list_t linked list
* @h: pointer to first node
*
* Return: size of list
*/
size_t print_list(const list_t *h)
{
size_t t = 0;
while (h)
{
_puts(convert_number(h->num, 10, 0));
_putchar(':');
_putchar(' ');
_puts(h->str ? h->str : "(nil)");
_puts("\n");
h = h->next;
t++;
}
return (t);
}
/**
* node_starts_with - function that returns node
* whose string starts with prefix
* @node: address of pointer to list head
* @prefix: string to match
* @c: the next character after prefix to match
*
* Return: match node or null
*/
list_t *node_starts_with(list_t *node, char *prefix, char c)
{
char *p = NULL;
while (node)
{
p = starts_with(node->str, prefix);
if (p && ((c == -1) || (*p == c)))
return (node);
node = node->next;
}
return (NULL);
}
/**
* get_node_index - function that gets the index of a node
* @head: address of tha pointer to list head
* @node: pointer to the node
*
* Return: index of node or -1
*/
ssize_t get_node_index(list_t *head, list_t *node)
{
size_t t = 0;
while (head)
{
if (head == node)
return (t);
head = head->next;
t++;
}
return (-1);
}