-
Notifications
You must be signed in to change notification settings - Fork 0
/
lists1.c
122 lines (105 loc) · 1.96 KB
/
lists1.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
#include "shell.h"
/**
* Determines the length of a linked list.
* @h: Pointer to the first node.
* Return: Size of the list.
*/
size_t list_len(const list_t *h)
{
size_t i = 0;
while (h)
{
h = h->next;
i++;
}
return i;
}
/**
* Returns an array of strings from the list->str.
* @head: Pointer to the first node.
* Return: Array of strings.
*/
char **list_to_strings(list_t *head)
{
list_t *node = head;
size_t i = list_len(head), j;
char **strs;
char *str;
if (!head || !i)
return NULL;
strs = malloc(sizeof(char *) * (i + 1));
if (!strs)
return NULL;
for (i = 0; node; node = node->next, i++)
{
str = malloc(_strlen(node->str) + 1);
if (!str)
{
for (j = 0; j < i; j++)
free(strs[j]);
free(strs);
return NULL;
}
str = _strcpy(str, node->str);
strs[i] = str;
}
strs[i] = NULL;
return strs;
}
/**
* Prints all elements of a list_t linked list.
* @h: Pointer to the first node.
* Return: Size of the list.
*/
size_t print_list(const list_t *h)
{
size_t i = 0;
while (h)
{
_puts(convert_number(h->num, 10, 0));
_putchar(':');
_putchar(' ');
_puts(h->str ? h->str : "(nil)");
_puts("\n");
h = h->next;
i++;
}
return i;
}
/**
* Returns the node whose string starts with the given prefix and next character.
* @node: Pointer to the list head.
* @prefix: String to match.
* @c: The next character after the prefix to match.
* Return: The matching 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;
}
/**
* Gets the index of a node in the list.
* @head: Pointer to the list head.
* @node: Pointer to the node.
* Return: Index of the node or -1.
*/
ssize_t get_node_index(list_t *head, list_t *node)
{
size_t i = 0;
while (head)
{
if (head == node)
return i;
head = head->next;
i++;
}
return -1;
}