简单字典实现(KV问题)

前端之家收集整理的这篇文章主要介绍了简单字典实现(KV问题)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

搜索二叉树基本概念请看上篇博客
这两个问题都是典型的K(key)V(value)问题,我们用KV算法解决

  1. 判断一个单词是否拼写正确:假设把所有单词都按照搜索树的性质插入到搜索二叉树中,我们判断一个单词拼写是否正确就是在树中查找该单词是否存在(查找key是否存在)。

结构声明下

  1. typedef char* KeyType;
  2. typedef struct BSTreeNode
  3. {
  4. struct BSTreeNode *_left;
  5. struct BSTreeNode *_right;
  6. KeyType _key;
  7. }BSTreeNode;

插入,查找函数代码如下:

  1. int BSTreeNodeInsertR(BSTreeNode **tree,KeyType key) //搜索树的插入
  2. {
  3. int tmp = 0;
  4. if(*tree == NULL)
  5. {
  6. *tree = BuyTreeNode(key);
  7. return 0;
  8. }
  9. tmp = strcmp((*tree)->_key,key);
  10. if (tmp>0)
  11. return BSTreeNodeInsertR(&(*tree)->_left,key);
  12. else if (tmp<0)
  13. return BSTreeNodeInsertR(&(*tree)->_right,key);
  14. else
  15. return -1;
  16. }
  17. BSTreeNode *BSTreeNodeFindR(BSTreeNode *tree,KeyType const key) //查找
  18. {
  19. int tmp = 0;
  20. if (!tree)
  21. return NULL;
  22. tmp = strcmp(tree->_key,key);
  23. if (tmp > 0)
  24. return BSTreeNodeFindR(tree->_left,key);
  25. else if (tmp < 0)
  26. return BSTreeNodeFindR(tree->_right,key);
  27. else
  28. return tree;
  29. }

测试代码

  1. void TestApplication()
  2. {
  3. BSTreeNode *tree = NULL;
  4. BSTreeNodeInsertR(&tree,"hello");
  5. BSTreeNodeInsertR(&tree,"world");
  6. BSTreeNodeInsertR(&tree,"int");
  7. BSTreeNodeInsertR(&tree,"char");
  8. BSTreeNodeInsertR(&tree,"float");
  9. BSTreeNodeInsertR(&tree,"double");
  10. printf("%s \n",BSTreeNodeFindR(tree,"char")->_key);
  11. printf("%s \n","double")->_key);
  12. printf("%s \n","int")->_key);
  13. printf("%s \n","float")->_key);
  14. printf("%s \n","hello")->_key);
  15. printf("%s \n","world")->_key);
  16. printf("%p \n","chars"));
  17. printf("%p \n","str"));
  18. }

测试结果:

检查单词是否拼写正确


2. 请模拟实现一个简单的字典(简单的中英文字典)

结构构建

  1. typedef char* KeyType;
  2. typedef int ValueType;
  3. typedef struct BSTreeNode
  4. {
  5. struct BSTreeNode *_left;
  6. struct BSTreeNode *_right;
  7. KeyType _key;
  8. ValueType _count;
  9. }BSTreeNode;

查找函数与上面相同,插入函数有所改变。

  1. int BSTreeNodeInsertR(BSTreeNode **tree,KeyType key,ValueType value) //搜索树的插入
  2. {
  3. int tmp = 0;
  4. if(*tree == NULL)
  5. {
  6. *tree = BuyTreeNode(key,value);
  7. return 0;
  8. }
  9. tmp = strcmp((*tree)->_key,key,value);
  10. else if (tmp<0)
  11. return BSTreeNodeInsertR(&(*tree)->_right,value);
  12. else
  13. return -1;
  14. }

测试代码

  1. void test()
  2. {
  3. BSTreeNode *tree = NULL;
  4. BSTreeNodeInsertR(&tree,"hello","你好");
  5. BSTreeNodeInsertR(&tree,"world","世界");
  6. BSTreeNodeInsertR(&tree,"char","字符");
  7. BSTreeNodeInsertR(&tree,"int","整形");
  8. BSTreeNodeInsertR(&tree,"float","浮点型");
  9. printf("%s \n","char")->_value);
  10. printf("%s \n","int")->_value);
  11. printf("%s \n","float")->_value);
  12. printf("%s \n","hello")->_value);
  13. printf("%s \n","world")->_value);
  14. printf("%p \n","double"));
  15. }

测试结果

中英文字典

构建测试案例尽量构建全面,防止特殊情况被忽略。

猜你在找的数据结构相关文章