diff --git a/src/trie.c b/src/trie.c index ca71340..f5bf81a 100644 --- a/src/trie.c +++ b/src/trie.c @@ -60,53 +60,25 @@ Trie *trie_new(void) return new_trie; } -static void trie_free_list_push(TrieNode **list, TrieNode *node) +static void free_node_recursive(TrieNode *node) { - node->next[0] = *list; - *list = node; -} + int i; -static TrieNode *trie_free_list_pop(TrieNode **list) -{ - TrieNode *result; + if (node == NULL) { + return; + } - result = *list; - *list = result->next[0]; + /* Free all subnodes */ + for (i = 0; i < 256; ++i) { + free_node_recursive(node->next[i]); + } - return result; + free(node); } void trie_free(Trie *trie) { - TrieNode *free_list; - TrieNode *node; - int i; - - free_list = NULL; - - /* Start with the root node */ - if (trie->root_node != NULL) { - trie_free_list_push(&free_list, trie->root_node); - } - - /* Go through the free list, freeing nodes. We add new nodes as - * we encounter them; in this way, all the nodes are freed - * non-recursively. */ - while (free_list != NULL) { - node = trie_free_list_pop(&free_list); - - /* Add all children of this node to the free list */ - for (i = 0; i < 256; ++i) { - if (node->next[i] != NULL) { - trie_free_list_push(&free_list, node->next[i]); - } - } - - /* Free the node */ - free(node); - } - - /* Free the trie */ + free_node_recursive(trie->root_node); free(trie); }