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);
}
}
- linux 红黑树代码
- linux内核中的红黑树代码解析
- 【Linux】Linux 统计代码行数
- linux网络代码学习
- linux代码大全
- Linux内核代码风格
- Linux内核代码风格
- Linux启动代码分析
- Linux 内核代码风格
- linux 清屏代码
- 两段Linux代码
- linux/Makefile 代码注释
- Linux 汇编代码
- linux indent格式化代码
- Linux Kernel 代码风格
- Linux代码阅读器
- linux的shell代码
- linux 0.11 引导代码
- Binder源码分析之驱动层(原)
- Binder源码分析之Native层(原)
- 让你的「微信小程序」运行在Chrome浏览器上,让我们使用WebStorm
- Binder源码分析之Java层(原)
- Unity3D 5.3 新版AssetBundle使用方案及策略
- linux 红黑树代码
- Coursera Machine Learning Week 7 - Support Vector Machines
- 痛悟的一天_更新
- Java学习笔记
- An Introduction to Interactive Programming in Python (Part 1) - Week 1
- [LeetCode238]Product of Array Except Self
- SQL 数据库 学习 006 如何设置一个用户名和密码
- 【codevs 1220】数字三角形
- 【NOIP2000】方格取数