From: Lukáš Jiřiště Date: Mon, 6 Apr 2026 11:08:25 +0000 (+0200) Subject: Implement the queue structure X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=HEAD;p=Libft.git Implement the queue structure It is the same as stack except for the names and a single line of code that places the new elements at the end instead of the beginning. Maybe there is an elegant refactor that would unify these. --- diff --git a/Makefile b/Makefile index b158667..b79304a 100644 --- a/Makefile +++ b/Makefile @@ -16,6 +16,7 @@ SRCDIR := ft_gen ft_math ft_str ft_mem ft_io ft_check ft_conv \ ft_lst ft_arr ft_parse ft_struct SRCstruct:= ft_stack.c \ + ft_queue.c \ ft_tree_init.c \ ft_tree_access_root.c \ ft_tree_append_child.c \ diff --git a/ft_struct/ft_queue.c b/ft_struct/ft_queue.c new file mode 100644 index 0000000..1bf9635 --- /dev/null +++ b/ft_struct/ft_queue.c @@ -0,0 +1,44 @@ +#include "ft_struct.h" + +t_ft_stat ft_queue_init(t_queue *queue, size_t el_size) +{ + return (ft_llist_init(&queue->list, el_size)); +} + +t_ft_stat ft_queue_enq(t_queue *queue, void *element) +{ + t_llist_node *new_node; + + if (!queue || !element) + { + return (invalid_input); + } + new_node = ft_llist_insert(&queue->list, element); + if (!new_node) + { + return (alloc_fail); + } + return (success); +} + +void *ft_queue_front(t_queue *queue) +{ + if (!queue->list.head) + return (NULL); + return (ft_llist_access(queue->list.head)); +} + +void *ft_queue_deq(t_queue *queue) +{ + void *res; + + res = ft_queue_front(queue); + ft_llist_delete_head(&queue->list, NULL); + return (res); +} + +void ft_queue_free(t_queue *queue, void (*free_el)(void *)) +{ + ft_llist_free(&queue->list, free_el); + return ; +} diff --git a/inc/ft_struct.h b/inc/ft_struct.h index 1495cbf..79ac51a 100644 --- a/inc/ft_struct.h +++ b/inc/ft_struct.h @@ -60,6 +60,17 @@ void *ft_stack_top(t_stack *stack); void *ft_stack_pop(t_stack *stack); void ft_stack_free(t_stack *stack, t_free_fun free_el); +typedef struct s_queue +{ + t_llist list; +} t_queue; + +t_ft_stat ft_queue_init(t_queue *queue, size_t el_size); +t_ft_stat ft_queue_enq(t_queue *queue, void *element); +void *ft_queue_front(t_queue *queue); +void *ft_queue_deq(t_queue *queue); +void ft_queue_free(t_queue *queue, t_free_fun free_el); + // t_vec reserves memory for 8 elements at first // it may be beneficial to add a member defining the number of children // and let a function reserve that number in the t_vec to save some space