歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言用二叉樹統計一個源文件中每個單詞的次數

C語言用二叉樹統計一個源文件中每個單詞的次數

日期:2017/3/1 10:08:06   编辑:Linux編程

由於出現的單詞不確定,所以用二叉樹實現:

  1. //TreeNode.h
  2. typedef struct _TreeNode
  3. {
  4. int count; //出現的次數
  5. char* word;//單詞本身
  6. struct _TreeNode* left;
  7. struct _TreeNode* right;
  8. }TreeNode;
  9. //給TreeNode分配內存
  10. TreeNode* talloc(void)
  11. {
  12. return (TreeNode*)malloc(sizeof(TreeNode));
  13. }
  14. //打印tree
  15. void tprint(TreeNode* root)
  16. {
  17. //打印left->self->right
  18. if(root!=NULL)
  19. {
  20. tprint(root->left);
  21. printf("%4d %s\n",root->count,root->word);
  22. tprint(root->right);
  23. }
  24. }
  25. //把單詞添加節點的合適位置
  26. TreeNode* addNode(TreeNode* node,const char* word)
  27. {
  28. int con;
  29. TreeNode* tmp;
  30. if(node==NULL)
  31. {
  32. node = talloc();
  33. node->count=1;
  34. node->word=strdup(word);
  35. node->left=node->right=NULL;
  36. }else if((con=strcmp(word,node->word))<0)
  37. {
  38. tmp = addNode(node->left,word);
  39. node->left=tmp;
  40. }else if(con>0)
  41. {
  42. tmp = addNode(node->right,word);
  43. node->right=tmp;
  44. }else{
  45. node->count++;
  46. }
  47. return node;
  48. }
  49. /**
  50. 從指定的流中讀取單詞
  51. */
  52. int getWord(char* ch,size_t n,FILE* f)
  53. {
  54. int c;
  55. char* p = ch;
  56. while(isspace(c=fgetc(f)))
  57. ;
  58. if(c!=EOF)
  59. *p++=c;
  60. if(!isalpha(c))
  61. {
  62. *p='\0';
  63. return c;
  64. }
  65. for(;--n>0;p++)
  66. {
  67. if(!isalnum(*p=fgetc(f)))
  68. {
  69. ungetc(*p,f);
  70. break;
  71. }
  72. }
  73. *p='\0';
  74. return c;
  75. }
  76. //是否tree占用的內存
  77. void treeFree(TreeNode* root)
  78. {
  79. if(root!=NULL)
  80. {
  81. treeFree(root->left);
  82. free(root->word); //釋放節點的word占用的內存
  83. free(root); //是否節點占用的內存
  84. treeFree(root->right);
  85. }
  86. }
  87. //Test.c
  88. #include <stdio.h>
  89. #include <stdlib.h>
  90. #include "TreeNode.h"
  91. #define MAX 100
  92. int main(int argc, char *argv[])
  93. {
  94. FILE* f;
  95. char w[MAX]={0};
  96. char* fname="TreeNode.h";
  97. if((f=fopen(fname,"r"))!=NULL)
  98. {
  99. TreeNode* root = NULL;
  100. while((getWord(w,MAX,f)!=EOF))
  101. {
  102. if(isalpha(w[0]))
  103. root = addNode(root,w);
  104. }
  105. tprint(root);
  106. treeFree(root);
  107. fclose(f);
  108. }else{
  109. printf("open %s error\n",fname);
  110. }
  111. getchar();
  112. return 0;
  113. }
Copyright © Linux教程網 All Rights Reserved