This repository was archived by the owner on Oct 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpush.c
122 lines (115 loc) · 2.74 KB
/
push.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
/* ************************************************************************** */
/* */
/* :::::::: */
/* push.c :+: :+: */
/* +:+ */
/* By: fbes <fbes@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2021/06/10 18:41:53 by fbes #+# #+# */
/* Updated: 2021/11/01 21:45:31 by fbes ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "push_swap.h"
/**
* Add a link or a number to the top of a stack
* @param *s The stack to add the link to
* @param *link The link to add, can be NULL
* @param n The number to add to the stack in case *link == NULL
* @return Returns 1 on success, 0 on failure
*/
int push(t_stack *s, t_link *link, int n)
{
if (!link)
{
link = malloc(sizeof(t_link));
if (link)
{
link->num = n;
link->id = -1;
}
}
if (link)
{
link->next = s->top;
link->prev = NULL;
if (s->top != NULL)
s->top->prev = link;
s->top = link;
s->size += 1;
return (1);
}
return (0);
}
/**
* Push the top from stack a to stack B and print pa
* @param *a The stack to push to
* @param *b The stack to pop from
*/
void pa(t_stack *a, t_stack *b)
{
if (b->size > 0)
{
push(a, pop(b), -1);
write(1, "pa\n", 3);
}
}
/**
* Push the top from stack a to stack B and print pb
* @param *a The stack to pop from
* @param *b The stack to push to
*/
void pb(t_stack *a, t_stack *b)
{
if (a->size > 0)
{
push(b, pop(a), -1);
write(1, "pb\n", 3);
}
}
/**
* Push the top from one stack to the other stack and print p<s2->id>
* @param *s1 The stack to pop from
* @param *s2 The stack to push to
*/
void pf(t_stack *s1, t_stack *s2)
{
if (s1->size > 0)
{
push(s2, pop(s1), -1);
write(1, "p", 1);
write(1, &(s2->id), 1);
write(1, "\n", 1);
}
}
/**
* Push the smallest link from stack a to stack b with the least amount of steps
* @param *a Stack A to pop from
* @param *b Stack B to push to
*/
void push_smallest_to_b(t_stack *a, t_stack *b)
{
t_link *smallest;
int steps;
if (a->size < 1)
return ;
smallest = get_stack_smallest(a);
steps = get_min_steps_to_reach(a, smallest);
if (steps > 0)
{
while (steps > 0)
{
ra(a);
steps--;
}
}
else if (steps < 0)
{
while (steps < 0)
{
rra(a);
steps++;
}
}
pb(a, b);
}