|
| 1 | +/* ************************************************************************** */ |
| 2 | +/* */ |
| 3 | +/* ::: :::::::: */ |
| 4 | +/* ft_lstdup.c :+: :+: :+: */ |
| 5 | +/* +:+ +:+ +:+ */ |
| 6 | +/* By: ldulling <ldulling@student.42.fr> +#+ +:+ +#+ */ |
| 7 | +/* +#+#+#+#+#+ +#+ */ |
| 8 | +/* Created: 2024/02/11 00:35:12 by ldulling #+# #+# */ |
| 9 | +/* Updated: 2024/06/07 19:09:20 by ldulling ### ########.fr */ |
| 10 | +/* */ |
| 11 | +/* ************************************************************************** */ |
| 12 | + |
| 13 | +#include "libft.h" |
| 14 | + |
| 15 | +/** |
| 16 | + * The ft_lstdup function duplicates a singly linked list by creating new nodes |
| 17 | + * with the same content as the original list. The content of the new nodes is |
| 18 | + * created by calling the provided 'dup' function on the content of the original |
| 19 | + * nodes. |
| 20 | + * |
| 21 | + * @param lst The original list to be duplicated. |
| 22 | + * @param dup The function to duplicate the content of the nodes. |
| 23 | + * @param del The function to delete the content of the nodes in case of |
| 24 | + * failure. |
| 25 | + * |
| 26 | + * @return Returns a pointer to the first node of the new list, or NULL if |
| 27 | + * the list could not be duplicated. |
| 28 | + * |
| 29 | + */ |
| 30 | +t_list *ft_lstdup(t_list *lst, void *(*dup)(void *), void (*del)(void *)) |
| 31 | +{ |
| 32 | + t_list *cur; |
| 33 | + t_list *new_lst; |
| 34 | + t_list *new_lst_tail; |
| 35 | + void *new_content; |
| 36 | + |
| 37 | + if (lst == NULL || dup == NULL || del == NULL) |
| 38 | + return (NULL); |
| 39 | + new_lst = NULL; |
| 40 | + new_lst_tail = NULL; |
| 41 | + cur = lst; |
| 42 | + while (cur != NULL) |
| 43 | + { |
| 44 | + new_content = (*dup)(cur->content); |
| 45 | + if (new_content == NULL) |
| 46 | + return (ft_lstclear(&new_lst, del), NULL); |
| 47 | + if (!ft_lstnew_back_eff(&new_lst, &new_lst_tail, new_content)) |
| 48 | + return (del(new_content), ft_lstclear(&new_lst, del), NULL); |
| 49 | + cur = cur->next; |
| 50 | + } |
| 51 | + return (new_lst); |
| 52 | +} |
0 commit comments