⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 字典树实现源代码.c

📁 此代码是字典树的实现源代码
💻 C
字号:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

#define MAX  'z' - 'a' + 1
#define SLEN 11 
typedef struct zidian {
 struct zidian *next[MAX];
 char s[SLEN];
 int  isword;
} *Link,node;
Link init(void)           //创建一个新结点
{
 Link root = (Link)malloc(sizeof(node));
 int  i; 
 for (i = 0; i < MAX; i++) root->next[i] = NULL;
 root->isword = 0;
 return root;
} 
void insert(char path[], char s[],Link root)  //插入一个单词path[]表示插入路线  char表示插入单词
{
 Link t, p = root;
 int i, j, n = strlen(path); 
 
  for (i = 0; i < n; i++) 
  {
      if (p->next[path[i] - 'a'] == NULL)
	  {
        t = (Link)malloc(sizeof(node));
        for (j = 0; j < MAX; j++) t->next[j] = NULL;
         t->isword = 0; 
        p->next[path[i] - 'a'] = t;
	  }
       p = p->next[path[i] - 'a'];
  }
   p->isword = 1;
   strcpy(p->s, s);
}
char *find(char path[], int delflag,Link root)  //查找一个单词 查到后作标记
{
 Link p = root; 
 int i, n = strlen(path);
 i = 0;
 while (p && path[i]) p = p->next[path[i++] - 'a'];
 if (p && p->isword) {
  p->isword = delflag;
  return p->s;
 }
 return NULL; 
}
void del(Link root)                            //毁掉这棵树
{
 int i; 

 if (!root) return;
 for (i = 0; i < MAX; i++)
  if (root->next[i]) del(root->next[i]);
 free(root->next[i]);
}
int main(void)
{
 char line[256], s1[256], s2[256];
 char *s; 
 Link root;

 root = init();
 while (gets(line)) {
  if (sscanf(line, "%s %s", s1, s2) != 2) break;
  insert(s2, s1,root);                 //插入单词
 }
 while (scanf("%s", s1) == 1) {
  s = find(s1, 1 ,root);               ///找单词
  if (s == NULL) printf("eh\n"); 
  else printf("%s\n", s);
 }
 return 0;
}

//////////////////////////////////////////////
字典树存储每个单词到树中  然后在树中找单词

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -