fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct node {
  6. char *s;
  7. struct node *next;
  8. struct node *lesser, *greater;
  9. };
  10.  
  11. static void print(const struct node *np)
  12. {
  13. if (!np)
  14. return;
  15. print(np->lesser);
  16. for (const struct node *ptr = np; ptr; ptr = ptr->next)
  17. fputs(ptr->s, stdout);
  18. print(np->greater);
  19. }
  20.  
  21. static struct node *install(struct node **tree, struct node *np)
  22. {
  23. int t;
  24.  
  25. np->greater = np->lesser = 0;
  26. while (*tree) {
  27. if (!(t = strcmp(np->s, (*tree)->s)))
  28. return *tree;
  29. tree = t < 0 ? &(*tree)->lesser : &(*tree)->greater;
  30. }
  31. *tree = np;
  32. return 0;
  33. }
  34.  
  35. static struct node *new(const char *s)
  36. {
  37. struct node *np;
  38.  
  39. if (!(np = malloc(sizeof *np)) || !(np->s = malloc(strlen(s) + 1)))
  40. exit(EXIT_FAILURE);
  41. strcpy(np->s, s);
  42. np->next = 0;
  43. return np;
  44. }
  45.  
  46. int main(void)
  47. {
  48. struct node *tree = 0, *np, *nt;
  49. char buf[8192];
  50.  
  51. while (fgets(buf, sizeof buf, stdin))
  52. if ((np = install(&tree, nt = new(buf)))) {
  53. nt->next = np->next; // Handle collision
  54. np->next = nt;
  55. }
  56. print(tree);
  57. return 0;
  58. }
Success #stdin #stdout 0s 1968KB
stdin
stu
def
abc
mno
vwx
yz
pqr
ghi
jkl
stdout
abc
def
ghi
jkl
mno
pqr
stu
vwx
yz