给定一个输入,我正在尝试构建一个应该水平生长的树,将转换应用于该输入和随之而来的孩子。
例如,给定输入“aab”和两个转换规则,例如:
ab -> bba
b -> ba
需要构建这样的树:
我已经编写了代码,但是按照我的方式,我的树是垂直工作的,我不希望这样。我需要它水平工作,但我看不到我将在哪里/如何编写递归。这是我现在所拥有的:
#include <string.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct t_string_node {
struct t_string_node *next;
char *value;
} string_node;
typedef struct t_transformation_rule {
struct t_transformation_rule *next;
char *needle;
char *replacement;
} transformation_rule;
void findTransformations(char *origin, string_node **transformations, char *needle, char *replacement)
{
char *str = origin;
for (char *p = str; *p != '\0'; p++) {
if (strncmp(p, needle, strlen(needle)) == 0) {
char *str_ = malloc(strlen(str)+1+strlen(replacement)-strlen(needle));
strcpy(str_, str);
char *p_ = p - str + str_;
memmove(p_+strlen(replacement), p_+strlen(needle), strlen(p_)+1-strlen(replacement));
memcpy(p_, replacement, strlen(replacement));
//Create new string node.
string_node *transformation;
transformation = malloc(sizeof(string_node));
transformation->value = str_;
transformation->next = NULL;
while (*transformations != NULL) {
transformations = &(*transformations)->next;
}
*transformations = transformation;
}
}
}
int hasTransformation(char *origin, char *target, transformation_rule *list_of_rules)
{
int level;
level = 0;
int found;
string_node *current;
current = malloc(sizeof(string_node));
current->value = origin;
current->next = NULL;
if(list_of_rules == NULL) {
if (strcmp(origin, target) == 0) {
printf("Solution in 0 steps");
return 1;
} else {
printf("No solution");
return 0;
}
}
string_node *transformations;
transformations = NULL;
while (current != NULL) {
findTransformations(current->value, target, &transformations, list_of_rules->needle, list_of_rules->replacement);
findTransformations(current->value, &transformations, list_of_rules->next->needle, list_of_rules->next->replacement);
current = current->next;
}
while (transformations != NULL) {
printf("%s \n", transformations->value);
transformations = transformations->next;
}
return 1;
}
void main()
{
char *input = "aab";
char *target = "bababab";
char *needle = "ab";
char *replacement = "bba";
transformation_rule *list_of_rules;
list_of_rules = NULL;
list_of_rules = malloc(sizeof(transformation_rule));
list_of_rules->needle = "ab";
list_of_rules->replacement = "bba";
list_of_rules->next = NULL;
//Create another rule
transformation_rule *new_rule;
new_rule = malloc(sizeof(transformation_rule));
new_rule->needle = "b";
new_rule->replacement = "ba";
new_rule->next = NULL;
list_of_rules->next = new_rule;
int has_trans;
has_trans = hasTransformation(input, target, list_of_rules);
}
任何人都可以帮助我意识到我将如何做到这一点,以便树水平而不是垂直生长?
谢谢