-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
129 lines (118 loc) · 2.55 KB
/
Copy pathstack.c
File metadata and controls
129 lines (118 loc) · 2.55 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
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hceviz <hceviz@student.42warsaw.pl> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/02/21 11:21:56 by hceviz #+# #+# */
/* Updated: 2025/02/24 09:25:52 by hceviz ### ########.fr */
/* */
/* ************************************************************************** */
#include "pushswap.h"
void stack_init(t_stack **stck, char **av)
{
long num;
int i;
i = 0;
while (av[i])
{
if (!is_num(av[i]))
{
write(2, "Error\n", 6);
free_and_exit(stck);
}
num = ft_atol(av[i]);
if (num > INT_MAX || num < INT_MIN)
{
write(2, "Error\n", 6);
free_and_exit(stck);
}
if (is_duplicate(av, num))
{
write(2, "Error\n", 6);
free_and_exit(stck);
}
append_node(stck, (int)num);
i++;
}
}
void append_node(t_stack **stck, int value)
{
t_stack *node;
if (!stck)
return ;
node = malloc(sizeof(t_stack));
if (!node)
return ;
node->value = value;
node->is_cheapest = false;
if (!(*stck))
{
*stck = node;
node->prev = node;
node->next = node;
node->index = 0;
}
else
{
(*stck)->prev->next = node;
node->prev = (*stck)->prev;
node->index = (*stck)->prev->index + 1;
node->next = (*stck);
(*stck)->prev = node;
}
}
int is_ascending(t_stack *stck)
{
t_stack *head;
head = stck;
if (stacklen(stck) == 1)
return (1);
if (stck->value > stck->next->value)
return (0);
else
stck = stck->next;
while (stck->next != head)
{
if (stck->value > stck->next->value)
return (0);
stck = stck->next;
}
return (1);
}
void pop_node(t_stack **stck)
{
t_stack *node;
t_stack *last;
if (!*stck)
return ;
node = *stck;
if ((*stck)->next == *stck)
*stck = NULL;
else
{
last = (*stck)->prev;
*stck = (*stck)->next;
(*stck)->prev = last;
last->next = *stck;
}
free(node);
update_index(*stck);
}
t_stack *get_cheapest(t_stack *a)
{
t_stack *a_head;
if (!a)
return (NULL);
a_head = a;
while (a)
{
if (a->is_cheapest)
return (a);
a = a->next;
if (a == a_head)
break ;
}
return (NULL);
}