fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>
  5.  
  6. #define N 1024
  7. char *myfgets(void) {
  8. static char buff[N];
  9. return fgets(buff, N, stdin);
  10. }
  11.  
  12. struct list {
  13. char *word;
  14. struct list *next;
  15. };
  16.  
  17. void myswap(struct list *p, struct list *q) {
  18. char *tmp;
  19. tmp = p->word;
  20. p->word = q->word;
  21. q->word = tmp;
  22. }
  23.  
  24. void bsort2(struct list *r, int sw) {
  25. struct list *p, *q;
  26. int c;
  27.  
  28. for (p = r, q = r->next; p->next != 0; p = p->next, q = q->next) { /* note: p->next != 0 */
  29. c = sw * strcmp(p->word, q->word);
  30. if (c > 0)
  31. myswap(p, q);
  32. }
  33. }
  34.  
  35. void bsort(struct list *root, int sw) {
  36. struct list *axis;
  37. if (root == 0)
  38. return;
  39. for (axis = root; axis != 0; axis = axis->next) {
  40. bsort2(root, sw);
  41. }
  42. }
  43.  
  44. void addword(struct list **root, char *word) {
  45. char *p;
  46. struct list *q;
  47. if ((p = malloc(strlen(word) + 1)) == 0) {
  48. fprintf(stderr, "memory full, aborted\n");
  49. exit(-1);
  50. }
  51. strcpy(p, word);
  52. if ((q = malloc(sizeof(struct list))) == 0) {
  53. fprintf(stderr, "memory full, aborted\n");
  54. exit(-1);
  55. }
  56. q->word = p;
  57. q->next = *root;
  58. *root = q;
  59. }
  60.  
  61. void dump(struct list *root) {
  62. if (root != 0) {
  63. printf("%s\n", root->word);
  64. dump(root->next);
  65. }
  66. }
  67.  
  68. void chop(char *p) {
  69. while (*p != 0)
  70. p++;
  71. p--;
  72. if (*p == '\n' || *p == '\r') *p = '\0';
  73. p--;
  74. if (*p == '\n' || *p == '\r') *p = '\0';
  75. *p = 0;
  76. }
  77.  
  78. void release(struct list **root) {
  79. struct list *p;
  80. if (*root != 0) {
  81. free((*root)->word);
  82. p = (*root)->next;
  83. (*root)->next = 0;
  84. free(*root);
  85. release(&p);
  86. }
  87. }
  88.  
  89. int main(int argc, char *argv[]) {
  90. char *p;
  91. struct list *root;
  92. int sw;
  93.  
  94. root = 0;
  95.  
  96. while ((p = myfgets()) != 0) {
  97. chop(p);
  98. addword(&root, p);
  99. }
  100. if (atoi(argv[1]) > 0)
  101. sw = +1;
  102. else
  103. sw = -1;
  104.  
  105. /* dump(root); */
  106. bsort(root, sw);
  107. dump(root);
  108. release(&root);
  109. }
  110. /* end */
  111.  
Runtime error #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
Standard output is empty