Advertisement
Guest User

Lab_8

a guest
Dec 9th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <clocale>
  4. #include <fstream>
  5. #include <string>
  6. #include "list.h"
  7.  
  8. using namespace std;
  9. struct trie {
  10.     char data = '\n';
  11.     list<trie *> childs;
  12. };
  13.  
  14. void add_key(trie *&root, string key) {
  15.     int lenght = key.length();
  16.     if (lenght > 0) {
  17.         node<trie *> *curr = root->childs.head;
  18.         for (; curr != NULL && curr->data->data != key[0]; curr = curr->next);
  19.         if (curr == NULL) {
  20.             trie *child = new trie;
  21.             child->data = key[0];
  22.             push_back(root->childs, child);
  23.             curr = root->childs.tail;
  24.         }
  25.         add_key(curr->data, key.substr(1, lenght - 1));
  26.     }
  27.     else {
  28.         trie *child = new trie;
  29.         child->data = '\0';
  30.         push_back(root->childs, child);
  31.     }
  32. }
  33.  
  34. void print(trie *root, string result = "") {
  35.     result += root->data;
  36.     if (!empty(root->childs)) {
  37.         for (node<trie *> *curr = root->childs.head; curr != NULL; curr = curr->next) {
  38.             print(curr->data, result);
  39.         }
  40.     }
  41.     if (root->data == '\0') {
  42.         for (int i = 1; i < result.length() - 1; ++i) {
  43.             cout << result[i];
  44.         }
  45.         cout << ' ';
  46.     }
  47. }
  48.  
  49. string reverse_string(string result) {
  50.     string result2;
  51.     for (int i = (result.length()) - 1; i >= 0; --i)
  52.         result2 += result[i];
  53.         return result2;
  54. }
  55.  
  56. void revers(trie *root, trie *&root2, string result = "") {
  57.     result += root->data;
  58.     if (!empty(root->childs)) {
  59.         for (node<trie *> *curr = root->childs.head; curr != NULL; curr = curr->next) {
  60.             revers(curr->data, root2, result);
  61.         }
  62.     }
  63.     if (root->data == '\0') {
  64.         result = reverse_string(result.substr(1, result.length() - 2));
  65.         add_key(root2, result);
  66.     }
  67. }
  68. int main() {
  69.     trie *root = new trie, *root2 = new trie;
  70.     string st;
  71.     ifstream in_file("input.txt");
  72.     while (in_file >> st)
  73.         add_key(root, st);
  74.     print(root);
  75.     cout << '\n';
  76.     revers(root, root2);
  77.     print(root2);
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement