Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include "tree.h"
- int main()
- {
- struct player arian;
- arian.name = "arian";
- insert_player(&arian);
- if(&arian == search_player("arian"))
- {
- printf("%s", "yes they are equal");
- }
- destroy();
- return 0;
- }
- #ifndef TREE_H_INCLUDED
- #define TREE_H_INCLUDED
- typedef long int name_t;
- typedef struct player
- {
- char* name;
- } *player_t;
- typedef struct node node;
- struct node
- {
- void* key;
- player_t player;
- node* left;
- node* right;
- };
- void destroy();
- void insert_player(player_t player);
- void insert(void* key, player_t player);
- long name_to_long(const char* s);
- node* search(void* key);
- player_t search_player(char* name);
- void _destroy(node * leaf);
- void _insert(void* key, node * leaf);
- node* _search(void* key, node * leaf);
- extern node* root;
- #endif // TREE_H_INCLUDED
- #include "tree.h"
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- node* root = NULL;
- long name_to_long(const char* s)
- {
- long l = 0L;
- int i;
- for(i = 0; i < strlen(s) && i < 12; ++i)
- {
- char c = s[i];
- l *= 37L;
- if(c >= 'A' && c <= 'Z')
- {
- l += (1+c) - 65;
- }
- else if(c>= 'a' && c <= 'z')
- {
- l += (1 + c) - 97;
- }
- else if(c >= '0' && c <= '9')
- {
- l += (27 + c) - 48;
- }
- while(l % 37L == 0L && l != 0L)
- {
- l /= 37L;
- }
- }
- return l;
- }
- void destroy()
- {
- _destroy(root);
- }
- void insert(void* key, player_t player)
- {
- if(root != NULL)
- {
- _insert(key, root);
- }
- else
- {
- root = malloc(sizeof(node));
- root->key = key;
- root->player = player;
- root->left = NULL;
- root->right = NULL;
- }
- }
- node* search(void* key)
- {
- return _search(key, root);
- }
- player_t search_player(char* name)
- {
- return _search((void*)name_to_long(name), root)->player;
- }
- void insert_player(player_t player)
- {
- insert((void*)name_to_long(player->name), player);
- }
- void _destroy(node * leaf)
- {
- if(leaf != NULL)
- {
- _destroy(leaf->left);
- _destroy(leaf->right);
- free(leaf);
- }
- }
- void _insert(void* key, node * leaf)
- {
- if(key < leaf->key)
- {
- if(leaf->left != NULL)
- {
- _insert(key, leaf->left);
- }
- else
- {
- leaf->left = malloc(sizeof(node));
- leaf->left->key = key;
- leaf->left->left = NULL;
- leaf->left->right = NULL;
- }
- }
- else if(key >= leaf->key)
- {
- if(leaf->right != NULL)
- {
- _insert(key, leaf->right);
- }
- else
- {
- leaf->right = malloc(sizeof(node));
- leaf->right->key = key;
- leaf->right->left = NULL;
- leaf->right->right = NULL;
- }
- }
- }
- node* _search(void* key, node * leaf)
- {
- if(leaf != NULL)
- {
- if(key == leaf->key)
- {
- return leaf;
- }
- if(key < leaf->key)
- {
- return _search(key, leaf->left);
- }
- else
- {
- return _search(key, leaf->right);
- }
- }
- else
- {
- return NULL;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement