-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_operations.c
132 lines (127 loc) · 2.46 KB
/
list_operations.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
127
128
129
130
131
132
#include "main.h"
/**
* insert_envlist_at_index - inserts a node at point specified by index
* @head: pointer to address of list
* @idx: point which node is to be inserted
* @s: node's data
* Return: pointer to modified node
*/
envlist_t *insert_envlist_at_index(envlist_t **head, int idx, char *s)
{
int i = 0;
envlist_t *node, *ptr = *head, *preptr = *head;
node = malloc(sizeof(envlist_t));
if (!node)
return (NULL);
node->var = _strdup(s);
node->length = _strlen(s);
node->next = NULL;
if (!ptr && !idx)
{
*head = node;
return (*head);
}
if (ptr && !idx)
{
node->next = *head;
*head = node;
return (*head);
}
if (!ptr && idx)
return (NULL);
while (i != idx && ptr)
{
i++;
preptr = ptr;
ptr = ptr->next;
}
if (i != idx)
return (ptr);
preptr->next = node;
node->next = ptr;
return (*head);
}
/**
* add_envlist - adds a node to the end of a singly linked list
* @head: pointer to node start
* @str: node string
* Return: pointer to new node
*/
envlist_t *add_envlist(envlist_t **head, char *str)
{
envlist_t *node;
envlist_t *ptr = *head;
char *string;
int string_length;
string_length = _strlen(str);
node = malloc(sizeof(envlist_t));
if (node == NULL)
return (NULL);
string = _strdup(str);
if (string == NULL)
{
free(node);
return (NULL);
}
node->var = string;
node->length = string_length;
node->next = NULL;
if (!ptr)
{
*head = node;
return (*head);
}
while (ptr->next)
ptr = ptr->next;
ptr->next = node;
return (*head);
}
/**
* delete_envlist_at_index - deletes a node from a list at index specified
* by index
* @head: pointer to address of list
* @index: index of node to be deleted
* Return: 1 if deletion is succesful and -1 if not
*/
int delete_envlist_at_index(envlist_t **head, int index)
{
envlist_t *ptr = *head, *preptr, *node;
int i = 0;
if (!(*head))
return (-1);
if (!index)
{
node = ptr->next;
free(ptr->var);
free(ptr);
*head = node;
return (1);
}
while (i != index && ptr)
{
i++;
preptr = ptr;
ptr = ptr->next;
}
if (i != index)
return (-1);
node = ptr->next;
free(ptr->var);
free(ptr);
preptr->next = node;
return (1);
}
/**
* create_envlist - initialises the environment variables list
* @envlist: environment list to be populated
* Return: the populated environment variables list
*/
envlist_t *create_envlist(envlist_t **envlist)
{
char **traverse;
for (traverse = environ; *traverse; traverse++)
{
add_envlist(envlist, *traverse);
}
return (*envlist);
}