-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
85 lines (71 loc) · 2.03 KB
/
stack.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abertran <abertran@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/20 22:10:18 by abertran #+# #+# */
/* Updated: 2023/02/23 18:34:18 by abertran ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
/* Creates a element(nodo) in the stack with the provided value.
Returns the newly created stack element. */
t_stack *stack_new(int value)
{
t_stack *new;
new = malloc(sizeof(t_stack));
if (!new)
return (NULL);
new->value = value;
new->index = 0;
new->pos = -1;
new->target = -1;
new->cost_a = -1;
new->cost_b = -1;
new->next = NULL;
return (new);
}
/* Adds an element to the bottom of a stack. */
void stack_add(t_stack **stack, t_stack *new)
{
t_stack *bottom;
if (!new)
return ;
if (!*stack)
{
*stack = new;
return ;
}
bottom = get_bottom(*stack);
bottom->next = new;
}
/* Returns the last element of the stack. */
t_stack *get_bottom(t_stack *stack)
{
while (stack && stack->next != NULL)
stack = stack->next;
return (stack);
}
/* Returns de element before the bottom element */
t_stack *before_bottom(t_stack *stack)
{
while (stack && stack->next->next != NULL)
stack = stack->next;
return (stack);
}
/* Returns the number of elements in a stack. */
int get_stack_size(t_stack *stack)
{
int size;
size = 0;
if (!stack)
return (0);
while (stack)
{
stack = stack->next;
size++;
}
return (size);
}