Push_swap/srcs/op.c

113 lines
2.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* op.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfirmin <lfirmin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/12 19:20:06 by lfirmin #+# #+# */
/* Updated: 2024/11/03 17:48:32 by lfirmin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/pushswap.h"
void add_stack(t_stack *stack, int value)
{
t_node *new_node;
t_node *current;
new_node = malloc(sizeof(t_node));
if (!new_node)
return ;
new_node->value = value;
new_node->next = NULL;
if (stack->top == NULL)
{
stack->top = new_node;
}
else
{
current = stack->top;
while (current->next != NULL)
{
current = current->next;
}
current->next = new_node;
}
stack->size++;
}
int swap(t_stack *stack)
{
t_node *first;
t_node *second;
if (stack->top == NULL || stack->top->next == NULL)
return (0);
first = stack->top;
second = first->next;
first->next = second->next;
second->next = first;
stack->top = second;
return (1);
}
int push(t_stack *stack_1, t_stack *stack_2)
{
t_node *first_1;
t_node *first_2;
t_node *tmp;
if (stack_1->top == NULL)
return (0);
first_1 = stack_1->top;
first_2 = stack_2->top;
tmp = first_1->next;
first_1->next = first_2;
stack_1->top = tmp;
stack_2->top = first_1;
stack_2->size++;
stack_1->size--;
return (1);
}
int rrotate(t_stack *stack)
{
t_node *first;
t_node *last;
t_node *before_last;
if (stack->size < 2)
return (0);
first = stack->top;
before_last = stack->top;
last = go_to(stack->top, stack->size);
before_last = go_to(stack->top, (stack->size - 1));
if (!last || !before_last)
return (-1);
before_last->next = NULL;
last->next = first;
stack->top = last;
return (1);
}
int rotate(t_stack *stack)
{
t_node *first;
t_node *last;
t_node *after_first;
if (stack->size < 2)
return (0);
first = stack->top;
last = stack->top;
last = go_to(stack->top, stack->size);
if (!last)
return (-1);
after_first = first->next;
last->next = first;
first->next = NULL;
stack->top = after_first;
return (1);
}