/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* wordlist.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: khais +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2025/02/13 17:07:01 by khais #+# #+# */ /* Updated: 2025/02/24 18:20:18 by khais ### ########.fr */ /* */ /* ************************************************************************** */ #include "wordlist.h" #include "libft.h" #include /* ** create a new wordlist element, with next set to null and word set to the ** passed worddesc. ** ** in case of error, return null */ t_wordlist *wordlist_create(t_worddesc *word) { t_wordlist *retvalue; retvalue = ft_calloc(1, sizeof(t_wordlist)); if (retvalue == NULL) return (NULL); retvalue->next = NULL; retvalue->word = word; return (retvalue); } /* ** free all memory associated with this wordlist. */ void wordlist_destroy(t_wordlist *wordlist) { t_wordlist *prev; while (wordlist != NULL) { worddesc_destroy(wordlist->word); prev = wordlist; wordlist = wordlist->next; free(prev); } } /* ** get the worddesc at position idx in the given wordlist. ** ** return null if out of range or wordlist is null */ t_worddesc *wordlist_get(t_wordlist *wordlist, int idx) { if (wordlist == NULL || idx < 0) return (NULL); while (idx > 0 && wordlist != NULL) { wordlist = wordlist->next; idx--; } if (wordlist == NULL) return (NULL); return (wordlist->word); } /* ** push the given worddesc to the end of the given wordlist. ** ** if wordlist is null, create a new wordlist. ** ** returns a pointer to the first element in the wordlist. ** ** if malloc failure is encountered, all memory for this wordlist is freed, and ** null is returned. */ t_wordlist *wordlist_push(t_wordlist *wordlist, t_worddesc *worddesc) { t_wordlist *start; if (wordlist == NULL) return (wordlist_create(worddesc)); start = wordlist; while (wordlist->next != NULL) wordlist = wordlist->next; wordlist->next = wordlist_create(worddesc); if (wordlist->next == NULL) return (wordlist_destroy(start), NULL); return (start); } /* ** remove and return the first element in the given wordlist ** ** If wordlist is empty, return null. */ t_worddesc *wordlist_pop(t_wordlist **wordlist) { t_wordlist *first; t_worddesc *word; if ((*wordlist) == NULL) return (NULL); first = *wordlist; (*wordlist) = first->next; word = first->word; free(first); return (word); }