Question

I'm a very beginner in C. However, I need a program that solves a problem for me. How can I do the following?

I need a tree structure. This is not traditional tree as every leaf can have various many leafs. Therefore every leaf should contain a linked list which contains the children of the leaf. In every link there is a char[][]-array and some int variables which tells how good a leaf is. And then I have to do some best-first search to find the best char[][]-array and output it. If I found a suitable array, I can stop the tree walk.

Was it helpful?

Solution

Me, I'd keep the linked list sorted at insertion time, so that you can always return the first list item in a tree node.

Something along the lines of

struct listnode {
    char** data;
    int quality;
    struct listnode* next;
};

struct treenode {
    struct treenode* left;
    struct treenode* right;
    int key;
    struct listnode* list;
};


struct treenode* tree_insert(struct treenode* root, int key, int quality, char** data)
{
    if(root == NULL) {
        root = treenode_alloc();
        root->key = key;
        root->list = list_insert(root->list, quality, data);
        return root;
    }

    if(key < root->key) {
        root->left = tree_insert(root->left, key, quality, data);
    } else if(key > root->key) {
        root->right = tree_insert(root->right, key, quality, data);
    } else {
      //key == root->key
      root->list = list_insert(root->list, quality, data);
    }
    return root;
}

struct listnode* list_insert(struct listnode* head, int quality, char** data) {
    struct listnode* prev = NULL;
    struct listnode* ins = NULL;
    struct listnode* ptr = NULL;
    if(head == NULL) {
        head = listnode_alloc();
        head->quality = quality;
        head->data = data;
        return head;
    }
    ptr = head;

    while(quality < ptr->quality) {
        if(ptr->next == NULL) { //we reached end of list
            ptr->next = list_insert(NULL, quality, data);
            return head;
        }

        prev = ptr;
        ptr = ptr->next;
    }

    //insertion into middle of list (before ptr, because ptr->quality >= quality)
    ins = listnode_alloc();
    ins->quality = quality;
    ins->data = data;
    ins->next = ptr;
    if(prev) {
        prev->next = ins;
    }
    return head;
}

OTHER TIPS

arrayindex is location info so more info than actual elements are index, arrayelement is data, good keywords fordfulkersson, trie datamodel for chemistry, b-tree for classic logic, breadthfirstsearch, concordance dbs, heapstructure or namely stack (LIFO)

study up on Data Structures & Algorithms... Wikipedia is a good place to look.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top