Change node counting system

This commit is contained in:
Dendy 2021-01-24 11:53:28 +01:00
parent f053b6cc5a
commit 1559a0d51c
Signed by: dendy
GPG Key ID: 0168B35FFD7F608F
3 changed files with 48 additions and 12 deletions

View File

@ -16,21 +16,26 @@ int main(int argc, char** argv){
NOD_NodeAddChild(node, node);
NOD_NodeAddChild(testchild, node);
NOD_NodeUnparent(justtotest);
printf("\nThe name of the node is \"%s\"\n", node->name);
for(int i = 0; i < node->childc; i++){
for(int i = 0; i < NOD_NodeChildCount(node); i++){
printf("Childnode: \"%s\"\n", node->childv[i]->name);
}
printf("\nThe name of the node is \"%s\"\n", node->name);
for(int i = 0; i < node->childc; i++){
for(int i = 0; i < NOD_NodeChildCount(node); i++){
printf("Childnode: \"%s\"\n", node->childv[i]->name);
}
printf("\nThe amount of children is %d, the real size is %d\n",
node->childc,
NOD_NodeChildCount(node),
(int)sizeof(testchild)
);
printf("\n");
NOD_PrintNodeTree(node);
NOD_DestroyNode(node);
NOD_DestroyNode(testchild);
return 0;

View File

@ -87,19 +87,44 @@ void NOD_NodeAddChild(NOD_Node* parent, NOD_Node* child){
}
}
void NOD_NodeRemoveChild(NOD_Node* parent, NOD_Node* child){
if(parent != NULL && child != NULL){
if(parent->childc < 1 || parent->childv == NULL){
void NOD_NodeUnparent(NOD_Node* node){
if(node != NULL && node->parent != NULL){
NOD_Node* parent = node->parent;
for(int i = 0; i < parent->childc; i ++){
if(parent->childv[i] == node){
parent->childv[i] = NULL;
/* Free allocated memory if last child */
if(i + 1 == parent->childc){
fprintf(stderr,
"NOD_Error: Cannot remove child \"%s\". Node \"%s\" has no children.\n",
child->name,
parent->name);
"NOD_Debug: Freeing last child of vector...\n");
parent->childv = realloc(parent->childv, sizeof(node) * parent->childc);
parent->childc--;
}
}
}
node->parent = NULL;
}
}
void NOD_PrintNodeTree(NOD_Node* node){
if(node != NULL){
printf("%s", node->name);
printf("\"%s\"\n", node->name);
for(int i = 0; i < node->childc; i++){
if(i+1 != node->childc) printf("├── ");
else printf("└── ");
printf("\"%s\"\n", node->childv[i]->name);
}
}
}
int NOD_NodeChildCount(NOD_Node* node){
unsigned int count = 0;
for(int i = 0; i < node->childc; i++){
if(node->childv[i] != NULL) count++;
}
return count;
}

View File

@ -4,6 +4,9 @@
typedef struct node{
char* name;
/** childc keeps track of allocated space,
not amount of children. For that use
NOD_NodeChildCount */
int childc;
struct node** childv;
struct node* parent;
@ -14,6 +17,9 @@ NOD_Node* NOD_CreateNode(char* name);
void NOD_DestroyNode(NOD_Node* node);
void NOD_NodeAddChild(NOD_Node* parent, NOD_Node* child);
void NOD_NodeRemoveChild(NOD_Node* parent, NOD_Node* child);
void NOD_NodeUnparent(NOD_Node* child);
void NOD_PrintNodeTree(NOD_Node* node);
int NOD_NodeChildCount(NOD_Node* node);
#endif // __NODE_H_