/** * trie_destroy_node: * @trie: A #Trie. * @node: A #TrieNode. * @value_destroy: A #GDestroyNotify or %NULL. * * Removes @node from the #Trie and releases all memory associated with it. * If the nodes value is set, @value_destroy will be called to release it. * * The reclaimation happens as such: * * 1) the node is unlinked from its parent. * 2) each of the children are destroyed, leaving us an empty chain. * 3) each of the allocated chain links are freed. * 4) the value pointer is freed. * 5) the structure itself is freed. */ static void trie_destroy_node (Trie *trie, TrieNode *node, GDestroyNotify value_destroy) { TrieNodeChunk *iter; TrieNodeChunk *tmp; g_assert(node); trie_node_unlink(node); while (node->chunk.count) { trie_destroy_node(trie, node->chunk.children[0], value_destroy); } for (iter = node->chunk.next; iter;) { tmp = iter; iter = iter->next; trie_free(trie, tmp); } if (node->value && value_destroy) { value_destroy(node->value); } trie_free(trie, node); }
void trie_destroy(trie_Node* root) { //用户接口,销毁trie树 int i = 0; for (i = 0; i < NODE_SIZE; i++) { trie_destroy_node(root->child[i]); } free(root->child); free(root->str); free(root); }
/** * trie_destroy: * @trie: A #Trie or %NULL. * * Frees @trie and all associated memory. */ void trie_destroy (Trie *trie) { if (trie) { trie_destroy_node(trie, trie->root, trie->value_destroy); trie->root = NULL; trie->value_destroy = NULL; g_free(trie); } }
void trie_destroy_node(trie_Node* root) { //递归删除节点 if (root == NULL) { return; } else { free(root->str); if (root->child != NULL) { int i = 0; for (i = 0; i < NODE_SIZE; i++) { trie_destroy_node(root->child[i]); } free(root->child); } free(root); return; } }
/** * trie_remove: * @trie: A #Trie. * @key: The key to remove. * * Removes @key from @trie, possibly destroying the value associated with * the key. * * Returns: %TRUE if @key was found, otherwise %FALSE. */ gboolean trie_remove (Trie *trie, const gchar *key) { TrieNode *node; g_return_val_if_fail(trie, FALSE); g_return_val_if_fail(key, FALSE); node = trie->root; while (*key && node) { node = trie_find_node(trie, node, *key); key++; } if (node && node->value) { if (trie->value_destroy) { trie->value_destroy(node->value); } node->value = NULL; if (!node->chunk.count) { while (node->parent && node->parent->parent && !node->parent->value && (node->parent->chunk.count == 1)) { node = node->parent; } trie_destroy_node(trie, node, trie->value_destroy); } return TRUE; } return FALSE; }