我正在尝试将字符串插入到其他字符串的链接列表中。 目标是让用户输入他们想要的任何字符串 (str_insert(。然后,用户必须输入要在哪个单词后插入字符串 (new_node(。
不幸的是,代码设法插入单词,但它只将其插入第二个位置。用于插入单词的函数称为插入。
typedef struct dll {
char data;
int count;
struct dll* next;
} dll;
typedef struct dictionary {
dll * data;
struct dictionary* next;``
struct dictionary* prev;
} dictionary;
dll* entry(){
char data = getc(stdin);
if (data != 'n'){
dll* curr = create_dico(data);
curr->next=entry();
return curr;
}
return NULL;
}
dictionary* insertion(dictionary *dico) {
printf("Please enter the string you want to insert in your already
existing list: n");
dictionary * str_insert = malloc(sizeof(dictionary));
str_insert->data = entry();
str_insert->next = NULL;
printf("Please enter after which word you would like to insert the
previous entry: n");
dictionary* new_node =(dictionary*)malloc(sizeof(dictionary));
new_node->data = entry();
new_node->next = dico->next;
new_node->prev = dico;
if (dico->next != NULL) {
str_insert->next = dico->next;
dico->next = str_insert;
}
}
我设法通过实现另一个将输入与现有列表进行比较的函数来使其工作。
这是最终结果:
dictionary* research(dictionary* dico, dll *search){
dll *save = search;
while (dico != NULL) {
dll *tmp = dico->data;
search = save;
while(tmp->data == search->data && tmp->next != NULL && search->next != NULL){
tmp = tmp->next;
search = search->next;
}
if(tmp->data == search->data){
return dico;
}
dico = dico->next;
}
return NULL;
}
void insertion(dictionary *dico) {
printf("Please enter the string you want to insert in your already existing list: n");
dictionary * str_insert = malloc(sizeof(dictionary));
str_insert->data = entry();
str_insert->next = NULL;
printf("Please enter after which word you would like to insert the previous entry: n");
dictionary* search =(dictionary*)malloc(sizeof(dictionary));
search->data = entry();
search = research(dico, search->data);
if (search == NULL){
printf("Sorry, this word isn't in the list.n");
}
else{
if(search->next != NULL){
search->next->prev = str_insert;
}
str_insert->next = search->next;
search->next = str_insert;
str_insert->prev = search;
}
}