I need to write AVL-tree with generic type in C. The best way I know is to use [ void* ] and to write some functions for creating, copying, assignment and destruction. Please, tell me some better way.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I will give you an example on how you can achieve generics functionality in C. The example is on a linked list, but I am sure you can adapt it on your AVL tree if necessary.
First of all you will need to define a structure for list element. A possible (most simple implementation):
Where ‘data’ will act as the “container” where you are going to keep your information, and ‘next’ is the reference to the direct linked element. (NOTE: Your binary tree element should include a reference to the right / left children elements).
After you create you element structure, you will need to create your list structure. A good practice is to have some members that are pointing to functions: destructor (needed to free the memory being hold by ‘data’), and comparator (to be able to compare two of your list elements).
A list structure implementation could look like this:
After you design your data structure, you should design your data structure interface. Let’s say our list will have the following, most simple, interface:
Where:
And now the functions implementation:
And now, how to use your simple generic linked list implementation. In the following example the list is acting like a stack:
Note that instead of “int *j” you can use a pointer that references more complex structures. If you do, don’t forget to modify your ‘list->destructor’ function accordingly.