linux 红黑树代码

来源:互联网 发布:文明太空mac版 编辑:程序博客网 时间:2024/06/01 20:18

这里提醒了我一点:linux内核中有个rbtree_test.c文件,可以编译成模块,加载和卸载,想知道他的函数是怎么工作的,最好就是装上这个模块跑一下。


这里是自己写个一个控制台程序,把linux的挖出来了,有几个文件:



接下来贴出 源代码(main.c):


/*
进行红黑树的linux代码测试
*/


#include "rbtree.h"
#include <stdio.h>


struct test_node
{
unsigned int key;
struct rb_node rb;
};


#define NUM_NODES 32
#define RB_ROOT (struct rb_root) { NULL, }
static struct rb_root root = RB_ROOT;
static struct test_node mn[NUM_NODES];


/*
实现一个在rbtree中进行查找的函数
*/
struct test_node* search(struct rb_root* root, unsigned int key)
{
struct rb_node* node = root->rb_node;


while(node)
{
struct test_node *data = rb_entry(node, struct test_node, rb);


if(key < data->key)
{
node = node->rb_left;
}
else if (key > data->key)
{
node = node->rb_right;
}
else
{
return data;
}
}


return NULL;
}


/*
实现一个在红黑树中进行插入节点的代码
*/
static void insert(struct test_node *node, struct rb_root *root)
{
struct rb_node **new = &root->rb_node, *parent = NULL;
unsigned int key = node->key;


while (*new) {
parent = *new;
if (key < rb_entry(parent, struct test_node, rb)->key)
new = &parent->rb_left;
else
new = &parent->rb_right;
}


rb_link_node(&node->rb, parent, new);
rb_insert_color(&node->rb, root);
}


/*
实现一个在红黑树中进行删除节点的代码
*/
static inline void erase(struct test_node *node, struct rb_root *root)
{
rb_erase(&node->rb, root);
}


void main(void)
{
/*
向红黑树种进行插入32个节点
*/
unsigned int i = 0;
for(; i < NUM_NODES; i++)
{
mn[i]->key = i;
insert(mn + i, &root);
}


/*
查找红黑树中一共有多少个节点
*/
struct rb_node *node;
for(node = rb_first(&root), node; node = rb_next(node))
{
printf("key = %d\n", rb_entry(node, struct test_node, rb)->key);
}


/*
删除一个节点
*/
printf("delete node 17:\n");
struct test_node *data = search(&root, 17);
if(data)
{
rb_erase(data, &root);
}


/*
查找红黑树中所有的节点
*/
for(node = rb_first(&root), node; node = rb_next(node))
{
printf("key = %d\n", rb_entry(node, struct test_node, rb)->key);
}
}

0 0
原创粉丝点击