1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
#ifndef _AVL_H
#define _AVL_H 1
/* Maximum AVL tree height. */
#ifndef AVL_MAX_HEIGHT
#define AVL_MAX_HEIGHT 92
#endif
#ifndef AVL_WITHOUT_PTHREADS
#include <pthread.h>
// #define AVL_LOCK_WITH_MUTEX 1
#ifdef AVL_LOCK_WITH_MUTEX
#define AVL_LOCK_INITIALIZER PTHREAD_MUTEX_INITIALIZER
#else /* AVL_LOCK_WITH_MUTEX */
#define AVL_LOCK_INITIALIZER PTHREAD_RWLOCK_INITIALIZER
#endif /* AVL_LOCK_WITH_MUTEX */
#else /* AVL_WITHOUT_PTHREADS */
#define AVL_LOCK_INITIALIZER
#endif /* AVL_WITHOUT_PTHREADS */
/* Data structures */
/* One element of the AVL tree */
typedef struct avl {
struct avl *avl_link[2]; /* Subtrees. */
signed char avl_balance; /* Balance factor. */
} avl;
/* An AVL tree */
typedef struct avl_tree {
avl *root;
int (*compar)(void *a, void *b);
} avl_tree;
typedef struct avl_tree_lock {
avl_tree avl_tree;
#ifndef AVL_WITHOUT_PTHREADS
#ifdef AVL_LOCK_WITH_MUTEX
pthread_mutex_t mutex;
#else /* AVL_LOCK_WITH_MUTEX */
pthread_rwlock_t rwlock;
#endif /* AVL_LOCK_WITH_MUTEX */
#endif /* AVL_WITHOUT_PTHREADS */
} avl_tree_lock;
/* Public methods */
/* Insert element a into the AVL tree t
* returns the added element a, or a pointer the
* element that is equal to a (as returned by t->compar())
* a is linked directly to the tree, so it has to
* be properly allocated by the caller.
*/
avl *avl_insert_lock(avl_tree_lock *t, avl *a);
avl *avl_insert(avl_tree *t, avl *a);
/* Remove an element a from the AVL tree t
* returns a pointer to the removed element
* or NULL if an element equal to a is not found
* (equal as returned by t->compar())
*/
avl *avl_remove_lock(avl_tree_lock *t, avl *a);
avl *avl_remove(avl_tree *t, avl *a);
/* Find the element into the tree that equal to a
* (equal as returned by t->compar())
* returns NULL is no element is equal to a
*/
avl *avl_search_lock(avl_tree_lock *t, avl *a);
avl *avl_search(avl_tree *t, avl *a);
/* Initialize the avl_tree_lock
*/
void avl_init_lock(avl_tree_lock *t, int (*compar)(void *a, void *b));
void avl_init(avl_tree *t, int (*compar)(void *a, void *b));
void avl_traverse_lock(avl_tree_lock *t, void (*callback)(void *));
void avl_traverse(avl_tree *t, void (*callback)(void *));
#endif /* avl.h */
|