forked from nathsotomayor/monty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonty_functions.c
133 lines (118 loc) · 2.17 KB
/
monty_functions.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
133
#include "monty.h"
/**
* push - adds a new node at the end of a stack_t list.
* @stack: pointer to head element of list
* @line_number: Line number of file
*
* Return: Nothing
*/
void push(stack_t **stack, unsigned int line_number)
{
stack_t *new = NULL, *tmp = *stack;
if (c_args.opcode[1] == NULL)
{
dprintf(STDERR_FILENO, "L%d: usage: push integer\n", line_number);
free_all();
}
is_number(line_number);
new = malloc(sizeof(stack_t));
if (new != NULL)
{
new->n = atoi(c_args.opcode[1]);
new->prev = NULL, new->next = NULL;
}
else
{
dprintf(STDERR_FILENO, "Error: malloc failed\n");
free(new);
free_all();
}
if (*stack == NULL)
{
new->prev = NULL;
*stack = new;
}
else
{
while (tmp->next != NULL)
tmp = tmp->next;
new->prev = tmp;
tmp->next = new;
}
}
/**
* pall - prints all elements of a stack ist.
* @stack: pointer to head element of stack list
* @line_number: Line number of file
*
* Return: Nothing
*/
void pall(stack_t **stack, unsigned int line_number)
{
int num = 0;
stack_t *tmp = *stack;
(void) line_number;
if (stack == NULL || *stack == NULL)
return;
while (tmp->next != NULL)
{
tmp = tmp->next;
}
for (num = 0; tmp != NULL; num++)
{
if (tmp == NULL)
return;
printf("%i\n", tmp->n);
tmp = tmp->prev;
}
}
/**
* free_stack - Free a list.
* @stack: pointer to head element of list
*
* Return: Nothing
*/
void free_stack(stack_t *stack)
{
stack_t *tmp;
if (stack == NULL)
return;
while (stack != NULL)
{
tmp = stack;
stack = stack->next;
free(tmp);
}
free(stack);
}
/**
* free_all - Free a list.
* Return: Nothing
*/
void free_all(void)
{
free_grid(c_args.opcode);
free_stack(c_args.head);
fclose(c_args.fd);
exit(EXIT_FAILURE);
}
/**
* is_number - Verify if opcode is a number
* @line_number: Error line number
*
* Return: Nothing
*/
void is_number(unsigned int line_number)
{
int i, start = 0;
if (c_args.opcode[1][0] == '-' && c_args.opcode[1][1] != 0)
start = 1;
for (i = start; c_args.opcode[1][i] != 0; i++)
{
if (c_args.opcode[1][i] < '0' || c_args.opcode[1][i] > '9')
{
dprintf(STDERR_FILENO, "L%d: usage: push integer\n", line_number);
free_all();
}
}
}