-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_init.c
More file actions
78 lines (70 loc) · 2.06 KB
/
stack_init.c
File metadata and controls
78 lines (70 loc) · 2.06 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack_init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jguacide <jguacide@student.codam.nl> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/03/29 09:59:14 by jguacide #+# #+# */
/* Updated: 2024/03/29 10:02:33 by jguacide ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
/*** METHOD ***
* stack_init initializes the stack with the command line arguments,
* while also checking for errors.
* We use ft_atol to convert the arguments given to numbers
* We use atol instead of atoi to avoid overflow while checking for MAX/MIN values
* The long obtained is then cast to an integer before being appended.
*/
void stack_init(t_list **a, char **argv)
{
int i;
long n;
n = 0;
i = 0;
while (argv[i] != NULL)
{
if (error_syntax(argv[i]))
free_errors(a);
n = ft_atol(argv[i]);
if (n > INT_MAX || n < INT_MIN)
free_errors(a);
if (error_duplicate(*a, (int)n))
free_errors(a);
append_node(a, (int)n);
i++;
}
}
long ft_atol(const char *s)
{
long n;
int i;
int sign;
i = 0;
sign = 1;
n = 0;
while (s[i] && ((s[i] >= 8 && s[i] <= 13) || s[i] == ' '))
i++;
if (s[i] == '+' || s[i] == '-')
{
if (s[i] == '-')
sign *= -1;
i++;
}
while (s[i] >= '0' && s[i] <= '9')
{
n = (n * 10) + (s[i] - '0');
i++;
}
return (n * sign);
}
// Appends n as a new node at the end of the stack.
void append_node(t_list **stack, int n)
{
t_list *new_node;
if (!stack)
return ;
new_node = ft_lstnew(n);
ft_lstadd_back(stack, new_node);
}