Push_swap/srcs/utils.c

93 lines
2.1 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfirmin <lfirmin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/14 00:09:54 by lfirmin #+# #+# */
/* Updated: 2024/11/03 17:51:14 by lfirmin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/pushswap.h"
t_node *go_to(t_node *top, int pos)
{
t_node *node;
int i;
if (pos < 1)
return (top);
node = top;
i = 1;
while (i < pos)
{
node = node->next;
i++;
}
return (node);
}
int valid_input(const char *str)
{
int i;
int sign_count;
long long num;
i = 0;
sign_count = 0;
while (str[i] == 32 || (str[i] >= 9 && str[i] <= 13))
i++;
while (str[i] == '+' || str[i] == '-')
{
sign_count++;
i++;
}
if (sign_count > 1 || str[i] == '\0')
return (ft_printf_fd(2, "Error\n"), 1);
while (str[i])
{
if (str[i] < '0' || str[i] > '9')
return (ft_printf_fd(2, "Error\n"), 1);
i++;
}
num = ft_atoll(str);
if (num > INT_MAX || num < INT_MIN)
return (ft_printf_fd(2, "Error\n"), 1);
return (0);
}
int in_stack(t_stack *stack, int n)
{
t_node *current;
current = stack->top;
while (current)
{
if (current->value == n)
{
ft_printf_fd(2, "Error\n");
return (1);
}
else
current = current->next;
}
return (0);
}
int is_sorted(t_stack *stack)
{
t_node *current;
if (!stack || !stack->top)
return (1);
current = stack->top;
while (current->next)
{
if (current->value > current->next->value)
return (0);
current = current->next;
}
return (1);
}