Guest User

Untitled

a guest
Apr 20th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. //copyright by Jeff.y.Lin
  2. //Date: 2018/04/13
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. typedef struct string
  7. {
  8. char word[101];
  9. int count;
  10. struct string *next;
  11. } string;
  12. void counting(string *ptr, char *line) //search the word is exists or not
  13. {
  14. string *new = malloc(sizeof(string));
  15. while (ptr != NULL) //if the word is exists, count++
  16. {
  17. if (strcmp(ptr->word, line) == 0)
  18. {
  19. ptr->count++;
  20. return;
  21. }
  22. else if (ptr->next == NULL)
  23. break;
  24. ptr = ptr->next;
  25. }
  26. strcpy(new->word, line); //if the word is not exists, malloc a new struct
  27. new->count = 1;
  28. ptr->next = new;
  29. new->next = NULL;
  30. }
  31. string *search(string *start, string *ptr) //search the previous node
  32. {
  33. while (start->next != ptr)
  34. start = start->next;
  35. return start;
  36. }
  37. void list(string *ptr)
  38. {
  39. while (ptr != NULL)
  40. {
  41. printf("%d %s\n", ptr->count, ptr->word);
  42. ptr = ptr->next;
  43. }
  44. }
  45. void sortandlist(string *start) //use insert sort and list
  46. {
  47. string *compare = start->next, *cur, *pre, *ptr, *pre_ptr;
  48. while (compare != NULL)
  49. {
  50. cur = compare; //compare is the current node, to control the step
  51. ptr = start;
  52. while (ptr != cur) //ptr is to compare with cur
  53. {
  54. if (ptr == start && ((cur->count > ptr->count) || (cur->count == ptr->count && strcmp(cur->word, ptr->word) < 0)))
  55. { //insert the cur in front of the start
  56. compare = compare->next;
  57. pre = search(start, cur);
  58. pre->next = cur->next;
  59. cur->next = start;
  60. start = cur;
  61. break;
  62. }
  63. else if (ptr != start && ((cur->count > ptr->count) || (cur->count == ptr->count && strcmp(cur->word, ptr->word) < 0)))
  64. { //insert the cur in front of the ptr
  65. compare = compare->next;
  66. pre = search(start, cur);
  67. pre->next = cur->next;
  68. pre_ptr = search(start, ptr);
  69. pre_ptr->next = cur;
  70. cur->next = ptr;
  71. break;
  72. }
  73. ptr = ptr->next;
  74. }
  75. if (ptr == cur)
  76. compare = compare->next;
  77. }
  78. list(start);
  79. }
  80. int main()
  81. {
  82. string *start = malloc(sizeof(string));
  83. char line[101];
  84. if (scanf("%s", line) == EOF)
  85. return 0;
  86. strcpy(start->word, line);
  87. start->count = 1;
  88. start->next = NULL;
  89. while (scanf("%s", line) != EOF)
  90. counting(start, line);
  91. sortandlist(start);
  92. return 0;
  93. }
Add Comment
Please, Sign In to add comment