ccmny

wordcount

Oct 22nd, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>
  5.  
  6. typedef struct node_t {
  7.     char * word;
  8.     int count;
  9.     struct node_t * left;
  10.     struct node_t * right;
  11. } Node;
  12.  
  13. void addword(char * word, Node * node);
  14. Node * node_new(char * word);
  15. void printnodes(Node * node);
  16.  
  17.  
  18. int main()
  19. {
  20.     Node * head = node_new("ala");
  21.     addword("ala", head);
  22.     addword("ma", head);
  23.     addword("kota", head);
  24.     addword("sierotka", head);
  25.     addword("ala", head);
  26.     addword("ma", head);
  27.     addword("rysia", head);
  28.  
  29.     printnodes(head);
  30.     return 0;
  31. }
  32.  
  33. void addword(char * word, Node * node)
  34. {
  35.     if(strcmp(node->word, word) == 0)
  36.     {
  37.         node->count++;
  38.     }
  39.     else if(strcmp(node->word, word) > 0)
  40.     {
  41.         if(node->right == NULL)
  42.             node->right = node_new(word);
  43.         else
  44.             addword(word, node->right);
  45.     }
  46.     else if(strcmp(node->word, word) < 0)
  47.     {
  48.         if(node->left == NULL)
  49.             node->left = node_new(word);
  50.         else
  51.             addword(word, node->left);
  52.     }
  53.  
  54. }
  55.  
  56. Node * node_new(char * word)
  57. {
  58.     Node * node = malloc(sizeof(Node));
  59.     node->word = malloc(strlen(word) + 1);
  60.     strcpy(node->word, word);
  61.     node->count = 1;
  62.     node->left = NULL;
  63.     node->right = NULL;
  64.     assert(node != NULL);
  65.     return node;
  66. }
  67.  
  68. void printnodes(Node * node)
  69. {
  70.     if(node != NULL)
  71.     {
  72.         printf("%-10s %10d\n", node->word, node->count);
  73.         printnodes(node->left);
  74.         printnodes(node->right);
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment