fork download
  1. #include <string>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. class Node
  6. {
  7. public:
  8. int count;
  9. Node *(children[26]); // array of pointers
  10. Node() { count = 0; for (int i = 0; i < 26; i++) children[i] = NULL; };
  11. };
  12.  
  13. void add(char *s, Node &n)
  14. {
  15. if (*s == 0) // null-terminator
  16. return;
  17. if (n.children[*s-'a'] == NULL)
  18. n.children[*s-'a'] = new Node();
  19. n.count++;
  20. add(s+1, *n.children[*s-'a']);
  21. }
  22.  
  23. void print(char *start, char *end, Node &n)
  24. {
  25. if (n.count == 1)
  26. {
  27. *end = 0; // null-terminator
  28. cout << start << endl;
  29. return;
  30. }
  31. for (int i = 0; i < 26; i++)
  32. {
  33. if (n.children[i] != NULL)
  34. {
  35. *end = (char)(i+'a');
  36. print(start, end+1, *n.children[i]);
  37. }
  38. }
  39. }
  40.  
  41. int main()
  42. {
  43. char *s = "stackoverflow";
  44. Node root;
  45. add(s, root);
  46. s = "standup";
  47. add(s, root);
  48. char output[1000]; // big buffer
  49. print(output, output, root);
  50. }
  51.  
  52.  
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
stac
stan