-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoken_helper.c
93 lines (86 loc) · 1.6 KB
/
token_helper.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
#include "main.h"
/**
* add_token_to_end - Adds a token to the end of a list
* @head: The head of the list of tokens
* @tkn: The token to add
*/
void add_token_to_end(token_t **head, token_t *tkn)
{
token_t *tail = NULL;
if (head != NULL)
{
tail = *head;
while ((tail != NULL) && (tail->next != NULL))
tail = tail->next;
if (tail == NULL)
*head = tkn;
else
tail->next = tkn;
}
else
{
head = &tkn;
}
}
/**
* create_token - Creates a new token
* @value: The value of the token
* @type: The type of the token
*
* Return: a pointer to the newly created token, otherwise NULL
*/
token_t *create_token(char *value, char type)
{
token_t *tkn = NULL;
tkn = malloc(sizeof(token_t));
if (tkn != NULL)
{
tkn->value = value;
tkn->type = type;
tkn->next = NULL;
}
return (tkn);
}
/**
* free_token_t - Frees a token_t list
* @head: The node at the beginning of the list
*/
void free_token_t(token_t **head)
{
if (head != NULL)
{
if (*head != NULL)
{
if ((*head)->next != NULL)
free_token_t(&((*head)->next));
if ((*head)->value != NULL)
free((*head)->value);
free(*head);
}
*head = NULL;
}
}
/**
* get_token_at_index - Retrieves the token at a given index
* @idx: The index of the token to retrieve
* @head: The pointer to the beginning of the list
*
* Return: The pointer to the token at the given index, otherwise NULL
*/
token_t *get_token_at_index(int idx, token_t **head)
{
int i = 0;
token_t *cur = NULL;
if (head != NULL)
{
cur = *head;
while (cur != NULL)
{
if (i == idx)
return (cur);
cur = cur->next;
i++;
}
}
return (NULL);
}