-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdlist.c
109 lines (85 loc) · 1.82 KB
/
cmdlist.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
#include "command.h"
/**
* add_cmd_end - add a command at the end of the list
* @headptr: a pointer to the address of the first list node
* @cmd: the cmd to add to the list
*
* Return: If memory allocation fails, return NULL. Otherwise, return the
* address of the new node.
*/
cmdlist_t *add_cmd_end(cmdlist_t **headptr, const char *cmd)
{
cmdlist_t *new;
if (!headptr)
return (NULL);
if (*headptr)
return (add_cmd_end(&((*headptr)->next), cmd));
new = malloc(sizeof(cmdlist_t));
if (!new)
return (NULL);
new->next = NULL;
new->tree = NULL;
new->tokens = tokenize(cmd);
if (!new->tokens)
{
free(new);
return (NULL);
}
*headptr = new;
return (new);
}
/**
* del_cmd - remove a command from a command list
* @headptr: the first node
* @index: argument passed
*
* Return: address of deleted node
*/
cmdlist_t *del_cmd(cmdlist_t **headptr, size_t index)
{
cmdlist_t *old;
if (!(headptr && *headptr))
return (NULL);
if (index)
return (del_cmd(&((*headptr)->next), index - 1));
old = *headptr;
*headptr = (*headptr)->next;
free_cmdtree(&(old->tree));
free_tokens(&(old->tokens));
free(old);
return (old);
}
/**
* pop_cmd - remove a node and retrieve it's tokens
* @headptr: the first node
*
* Return: command tokens
*/
char **pop_cmd(cmdlist_t **headptr)
{
cmdlist_t *pop;
char **tokens;
if (!(headptr && *headptr))
return (NULL);
pop = *headptr;
tokens = pop->tokens;
*headptr = (*headptr)->next;
free_cmdtree(&(pop->tree));
free(pop);
return (tokens);
}
/**
* free_cmdlist - free a linked list and and set head to NULL
* @headptr: the first node
*/
void free_cmdlist(cmdlist_t **headptr)
{
if (headptr && *headptr)
{
free_cmdlist(&((*headptr)->next));
free_cmdtree(&((*headptr)->tree));
free_tokens(&((*headptr)->tokens));
free(*headptr);
*headptr = NULL;
}
}