-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_lis2.c
124 lines (110 loc) · 2.09 KB
/
linked_lis2.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 "s_shell.h"
/**
* listLen - counts length of linked list
* @head: pointer to first node
*
* Return: size of list
*/
size_t listLen(const str_list_t *head)
{
size_t length = 0;
while (head)
{
head = head->next;
length++;
}
return (length);
}
/**
* listToString - returns an array of strings of the linked list
* @head: pointer to first node
*
* Return: array of strings
*/
char **listToString(str_list_t *head)
{
str_list_t *node = head;
size_t length = listLen(head), j;
char **result;
char *str;
if (!head || !length)
return (NULL);
result = malloc(sizeof(char *) * (length + 1));
if (!result)
return (NULL);
for (length = 0; node; node = node->next, length++)
{
str = malloc(_strlen(node->str) + 1);
if (!str)
{
for (j = 0; j < length; j++)
free(result[j]);
free(result);
return (NULL);
}
str = _strcpy(str, node->str);
result[length] = str;
}
result[length] = NULL;
return (result);
}
/**
* printList - prints all elements of linked list
* @head: pointer to first node
*
* Return: size of list
*/
size_t printList(const str_list_t *head)
{
size_t length = 0;
while (head)
{
_puts(convert_to_string(head->num, 10, 0));
_putchar(':');
_putchar(' ');
_puts(head->str ? head->str : "(nil)");
_puts("\n");
head = head->next;
length++;
}
return (length);
}
/**
* nodePrefix - returns node whose string starts with prefix
* @node: pointer to list head
* @pre: string to match
* @c: nrxt character after match prefix
*
* Return: last node, or null
*/
str_list_t *nodePrefix(str_list_t *node, char *pre, char c)
{
char *ptr = NULL;
while (node)
{
ptr = _starts_with(node->str, pre);
if (ptr && ((c == -1) || (*ptr == c)))
return (node);
node = node->next;
}
return (NULL);
}
/**
* getNodeIndex - gets the index of a node
* @head: pointer to head
* @node: pointer to the node
*
* Return: index of the node, or -1 on failure
*/
ssize_t getNodeIndex(str_list_t *head, str_list_t *node)
{
size_t index = 0;
while (head)
{
if (head == node)
return (index);
head = head->next;
index++;
}
return (-1);
}