Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <iostream>
- #include <clocale>
- #include <fstream>
- #include <string>
- #include "list.h"
- using namespace std;
- struct trie {
- char data = '\n';
- list<trie *> childs;
- };
- void add_key(trie *&root, string key) {
- int lenght = key.length();
- if (lenght > 0) {
- node<trie *> *curr = root->childs.head;
- for (; curr != NULL && curr->data->data != key[0]; curr = curr->next);
- if (curr == NULL) {
- trie *child = new trie;
- child->data = key[0];
- push_back(root->childs, child);
- curr = root->childs.tail;
- }
- add_key(curr->data, key.substr(1, lenght - 1));
- }
- else {
- trie *child = new trie;
- child->data = '\0';
- push_back(root->childs, child);
- }
- }
- void print(trie *root, string result = "") {
- result += root->data;
- if (!empty(root->childs)) {
- for (node<trie *> *curr = root->childs.head; curr != NULL; curr = curr->next) {
- print(curr->data, result);
- }
- }
- if (root->data == '\0') {
- for (int i = 1; i < result.length() - 1; ++i) {
- cout << result[i];
- }
- cout << ' ';
- }
- }
- string reverse_string(string result) {
- string result2;
- for (int i = (result.length()) - 1; i >= 0; --i)
- result2 += result[i];
- return result2;
- }
- void revers(trie *root, trie *&root2, string result = "") {
- result += root->data;
- if (!empty(root->childs)) {
- for (node<trie *> *curr = root->childs.head; curr != NULL; curr = curr->next) {
- revers(curr->data, root2, result);
- }
- }
- if (root->data == '\0') {
- result = reverse_string(result.substr(1, result.length() - 2));
- add_key(root2, result);
- }
- }
- int main() {
- trie *root = new trie, *root2 = new trie;
- string st;
- ifstream in_file("input.txt");
- while (in_file >> st)
- add_key(root, st);
- print(root);
- cout << '\n';
- revers(root, root2);
- print(root2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement