-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathavl-test.c
More file actions
92 lines (70 loc) · 1.58 KB
/
avl-test.c
File metadata and controls
92 lines (70 loc) · 1.58 KB
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
87
88
89
90
91
92
/*
* AVL Tree Internals
*
* Copyright (c) 2010-2023 Alexei A. Smekalkine <ikle@ikle.ru>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <capsa/avl.h>
struct node {
struct avl handle;
const char *key;
};
static struct avl *node_alloc (const void *key)
{
struct node *o;
if ((o = malloc (sizeof (*o))) == NULL)
return NULL;
o->key = key;
return &o->handle;
}
static void node_free (struct avl *node)
{
struct node *o = (void *) node; /* use container_of if you can */
free (o);
}
static int node_cmp (const void *key, const struct avl *node)
{
const struct node *o = (void *) node;
return strcmp (key, o->key);
}
static void tree_show (struct avl *node)
{
const struct node *o = (void *) node;
if (node == NULL)
return;
tree_show (node->child[0]);
printf ("%s\n", o->key);
tree_show (node->child[1]);
}
static const char *key[] = {
"test string #1",
"Lorem ipsum dolor sit amet",
"consectetur adipiscing elit",
"sed do eiusmod tempor incididunt",
"ut labore et dolore magna aliqua",
"test string #2",
NULL,
};
int main (int argc, char *argv[])
{
struct avl *root = NULL;
size_t i;
for (i = 0; key[i] != NULL; ++i)
if (avl_search (&root, key[i], node_cmp, node_alloc) == NULL) {
fprintf (stderr, "E: Cannot insert key into tree\n");
return 1;
}
printf ("Inserted keys:\n\n");
tree_show (root);
i = 2;
printf ("\nRemove %s\n", key[i]);
node_free (avl_remove (&root, key[i], node_cmp));
printf ("\nKeys after removal:\n\n");
tree_show (root);
avl_free (root, node_free);
return 0;
}