Linux内核学习之红黑树

Linux内核中的红黑树定义为:struct rb_node

 

  • 初始化红黑树

struct rb_root mytree = RB_ROOT;

 

假设有如下定义

typedef struct rbtree_test_s

{

char str[32];

struct rb_node rbnode;

int a;

}rbtree_test_t;

 

  • 操作红黑树

插入和查找数据,需要自己实现,代码如下:

int my_insert(struct rb_root *root, rbtree_test_t *data)
{
	struct rb_node **new = &(root->rb_node), *parent = NULL;

	/* Figure out where to put new node */
	while (*new) 
	{
		rbtree_test_t *this = container_of(*new, rbtree_test_t, rbnode);
		int result = strcmp(data->str, this->str);

		parent = *new;
		if (result < 0)
			new = &((*new)->rb_left);
		else if (result > 0)
			new = &((*new)->rb_right);
		else
			return 0;
	}

	/* Add new node and rebalance tree. */
	rb_link_node(&data->rbnode, parent, new);
	rb_insert_color(&data->rbnode, root);

	return 1;
}
rbtree_test_t *my_search(struct rb_root *root, char *string)
{
	struct rb_node *node = root->rb_node;

	while (node) {
		rbtree_test_t *data = container_of(node, rbtree_test_t, rbnode);
		int result;

		result = strcmp(string, data->str);

		if (result < 0)
			node = node->rb_left;
		else if (result > 0)
			node = node->rb_right;
		else
			return data;
	}
	return NULL;
}

删除数据:rb_erase

 

遍历红黑树的方式:

struct rb_node *node;
for (node = rb_first(&mytree); node; node = rb_next(node))
	printf("key=%s\n", rb_entry(node, rbtree_test_t, rbnode)->str);

 

  • 具体用法,详见下边的例子
int main(int argc, char** argv)
{
	rbtree_test_t a1={0};
	rbtree_test_t a2={0};
	rbtree_test_t a3={0};

	strcpy(a1.str, "a1");
	my_insert(&mytree, &a1);
	strcpy(a2.str, "a2");
	my_insert(&mytree, &a2);
	strcpy(a3.str, "a3");
	my_insert(&mytree, &a3);

	//遍历红黑树
	struct rb_node *node;
	for (node = rb_first(&mytree); node; node = rb_next(node))
		printf("key=%s\n", rb_entry(node, rbtree_test_t, rbnode)->str);

	printf("-----------------------\n");
	rbtree_test_t* p = my_search(&mytree, "a2");
	if (p)
	{
		strcpy(p->str, "hyq");
		//rb_erase(&p->rbnode, &mytree);
	}
	
	for (node = rb_first(&mytree); node; node = rb_next(node))
		printf("key=%s\n", rb_entry(node, rbtree_test_t, rbnode)->str);

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值