refactor nonbintree to c++

main
krutoykoder1337 2025-01-02 22:56:28 +03:00
parent 8db76bb70f
commit 732cd445fa
Signed by: krutoykoder1337
GPG Key ID: AB338614D40787D3
2 changed files with 20 additions and 83 deletions

View File

@ -1,72 +0,0 @@
#include <stdlib.h>
#include <string.h>
#include "nonbin_tree.h"
tree_node* create_tree(void* data){
tree_node* tree_root = malloc(sizeof(tree_node));
tree_root->child = NULL;
tree_root->id = 0;
tree_root->brother = NULL;
tree_root->data = data;
}
void add_tree_node(uint32_t* path, void* data, int path_len, tree_node* root){
tree_node* current_node = root;
tree_node* current;
tree_node* end_node;
char is_find;
for (int i = 1; i < path_len; i++){
if (current_node->child == NULL){
current_node->child = malloc(sizeof(tree_node));
current_node->child->id = path[i];
current_node->child->brother = NULL;
current_node->child->child = NULL;
}
current_node = current_node->child;
is_find = 0;
for (current = current_node; current != NULL; current = current->brother){
if (current->id == path[i]){
current_node = current;
is_find = 1;
break;
}
if (current->brother == NULL) end_node = current;
}
if (!is_find){
current = end_node;
current->brother = malloc(sizeof(tree_node));
current->brother->id = path[i];
current->brother->brother = NULL;
current->brother->child = NULL;
current = current->brother;
current_node = current;
}
}
current_node->data = data;
}
void* get_tree_node(uint32_t* path, int path_len, tree_node* root){
tree_node* current_node = root;
tree_node* current;
tree_node* end_node;
char is_find;
for (int i = 1; i < path_len; i++){
if (current_node->child == NULL){
return NULL;
}
current_node = current_node->child;
is_find = 0;
for (current = current_node; current != NULL; current = current->brother){
if (current->id == path[i]){
current_node = current;
is_find = 1;
break;
}
}
if (!is_find) return NULL;
}
return current_node->data;
}

View File

@ -1,14 +1,23 @@
#include <inttypes.h>
typedef struct tree_node
{
struct tree_node* child;
struct tree_node* brother;
uint32_t id;
void* data;
} tree_node;
#include <string>
#include <queue>
tree_node* create_tree(void* data);
void add_tree_node(uint32_t* path, void* data, int path_len, tree_node* root);
void* get_tree_node(uint32_t* path, int path_len, tree_node* root);
template<typename T> struct tree_node{
struct tree_node* child;
struct tree_node* brother;
std::string id;
T* data;
};
template<typename T> class NonBinTree{
public:
NonBinTree(T* data);
void add_url(std::string url, T* handler);
T* get_url(std::string url);
private:
void add_tree_node(std::queue<std::string> path, T* data);
T* get_tree_node(std::queue<std::string> path);
tree_node<T> *root = new tree_node<T>;
};