test.c 1.46 KB
Newer Older
Jack Moffitt's avatar
Jack Moffitt committed
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <stdio.h>
#include "avl.h"

#ifdef _WIN32
#define snprintf _snprintf
#endif

int _compare(void *compare_arg, void *a, void *b);
int _free(void *key);
int _printer(char *buff, void *key);

int main(int argc, char **argv)
{
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
    int i, max_nodes;
    avl_tree *tree;
    avl_node *node;

    max_nodes = 25;

    if (argc == 2) {
        max_nodes = atoi(argv[1]);
        if (max_nodes == 0)
            max_nodes = 10;
    }

    printf("avl test... max_nodes = %d...\n", max_nodes);

    tree = avl_tree_new(_compare, NULL);

    printf("Filling tree...\n");
    for (i = 0; i < max_nodes; i++) {
        avl_insert(tree, (void *)rand());
    }
    
    printf("Traversing tree...\n");
    node = avl_get_first(tree);
    while (node) {
        i = (int)node->key;

        printf("...%5d\n", i);

        node = avl_get_next(node);
    }

    printf("Trying to go backwards...\n");
    node = tree->root->right;
    while (node) {
        i = (int)node->key;
        printf("...%5d\n", i);
        node = avl_get_prev(node);
    }

    printf("Printing tree...\n");
    avl_print_tree(tree, _printer);

    avl_tree_free(tree, _free);
    
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
59 60 61 62
}

int _compare(void *compare_arg, void *a, void *b)
{
63
    int i, j;
Jack Moffitt's avatar
Jack Moffitt committed
64

65 66
    i = (int)a;
    j = (int)b;
Jack Moffitt's avatar
Jack Moffitt committed
67

68 69 70 71 72
    if (i > j)
        return 1;
    if (j > i)
        return -1;
    return 0;
Jack Moffitt's avatar
Jack Moffitt committed
73 74 75 76
}

int _free(void *key) 
{
77
    return 1;
Jack Moffitt's avatar
Jack Moffitt committed
78 79 80 81
}

int _printer(char *buff, void *key)
{
82
    return snprintf(buff, 25, "%d", (int)key);
Jack Moffitt's avatar
Jack Moffitt committed
83 84 85 86 87 88 89 90 91 92 93 94 95
}