main.cpp:
#gcc main.cpp rbtree.cpp rbtree.h
#./a.out
#include
#include
#include "rbtree.h"
struct my_node {
int data;
struct rb_node node;
};
struct rb_root groot=RB_ROOT;
void rb_traverse(struct rb_root *root)
{
struct my_node *entry;
struct rb_node *n;
for(n = rb_first(root);n;n=rb_next(n))
{
entry = rb_entry(n, struct my_node, node);
printf("%d--", entry->data);
}
}
void rb_add(struct rb_root *root, int data)
{
struct rb_node **p=&(root->rb_node);
struct rb_node *parent = NULL;
struct my_node *entry;
struct my_node *new_node=(struct my_node*)malloc(sizeof(struct my_node));
rb_init_node(&(new_node->node));
new_node->data = data;
while(*p)
{
parent = *p;
entry = rb_entry(parent, struct my_node,node);
if(entry->data > data)
p=&((*p)->rb_left);
else if (entry->data < data)
p=&((*p)->rb_right);
else
printf("node already exist\n");
}
rb_link_node(&new_node->node, parent, p);
rb_insert_color(&new_node->node, root);
}
int main()
{
int i;
for(i=20;i>10;i--)
rb_add(&groot, i);
for(i=10;i>0;i--)
rb_add(&groot, i);
for(i=30;i>20;i--)
rb_add(&groot, i);
rb_traverse(&groot);
return 0;
}
阅读(940) | 评论(0) | 转发(0) |