C-数据结构-retrieval搜索树

log

ant:a samll insect that lives in group
butterfly:a flying insect with a long thin body
cobra:a highly dangerous snake
monkey: a animal with short legs and long ears

trie.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define DESC_SIZE 256
#define KEY_SIZE  256
#define BUF_SIZE  512
#define FNAME 	  "log"	//当前路径的Log文件

struct node_st 
{
	struct node_st *ch[26];
	char desc[DESC_SIZE];
};

int get_word(FILE *fp,char *key,char *desc)
{
	char buf[BUF_SIZE];
	char *retp;
	int i,j;
	
	retp = fgets(buf,BUF_SIZE,fp);
	if(retp == NULL)
		return -1;
	
	for(i = 0;i < KEY_SIZE-1 && buf[i] != ':'; i++)
		key[i] = buf[i];
	key[i] = '\0';
	i++;
	for(j = 0 ;j < DESC_SIZE -1 && buf[i] !='\0';j++,i++)
		desc[j] = buf[i];
	desc[j] = '\0';
	return 0;
}

struct node_st *newnode()
{
	int i;
	struct node_st *node;
	node = malloc(sizeof(*node));
	if(node == NULL)
		return NULL;
	node->desc[0] = '\0';
	for(i =0;i<26;i++)
		node->ch[i] = NULL;
	return node;
}

int insert(struct node_st **root,char *key,char *desc)
{
	if(*root == NULL)
	{
		*root = newnode();
		if(*root == NULL)
			return -1;
	}
	if(*key == '\0')
	{
		strcpy((*root)->desc,desc);
		return 0;
	}
	return insert((*root)->ch + *key - 'a',key +1,desc);

}

char *find(struct node_st *root,char *key)
{
	if(root == NULL)
		return NULL;
	if(*key == '\0')
		return root->desc;
	return find(root->ch[*key-'a'],key +1);
}


int main()
{
	struct node_st *tree = NULL;
	int ret;
	FILE *fp;
	char desc[DESC_SIZE]={'\0'},key[KEY_SIZE]={'\0'};
	char *datap;
	
	fp = fopen(FNAME,"r");
	if(fp == NULL)
	{
		fprintf(stderr,"fopen:error!\n");
		exit(1);
	}
	
	while(1)
	{
		ret = get_word(fp,key,desc);
		if(ret == -1)
			break;
		//puts(key);
		//puts(desc);
		insert(&tree,key,des);
		
		
	}
	datap = find(tree,"monkey");
	if(datap == NULL)
		printf("can not find \n");
	else 
		puts(datap);


	fclose(fp);
	exit(0);
}


补充说明

要理解 struct node_st *ch[26]; 的含义,我们可以逐步解析这个定义,并结合代码示例说明它是如何工作的。这里我们一步一步地解释。

逐步理解 struct node_st *ch[26];
指针数组:

ch 是一个数组,它包含 26 个元素。
数组的每个元素都是一个指向 struct node_st 类型的指针。
struct node_st 是一个结构体类型,表示前缀树的节点。
struct node_st 是一个包含指针数组 ch 和描述字符串 desc 的结构体。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值