C 在单个链接列表中插入字符串
我正在尝试将一个字符串插入到其他字符串的链接列表中。 目标是让用户输入他们想要的任何字符串(str_insert)。然后,用户必须输入要插入字符串的单词(新节点) 不幸的是,代码成功地插入了单词,但它只将其插入到第二个位置。用于插入单词的函数称为插入C 在单个链接列表中插入字符串,c,string,linked-list,C,String,Linked List,我正在尝试将一个字符串插入到其他字符串的链接列表中。 目标是让用户输入他们想要的任何字符串(str_insert)。然后,用户必须输入要插入字符串的单词(新节点) 不幸的是,代码成功地插入了单词,但它只将其插入到第二个位置。用于插入单词的函数称为插入 typedef struct dll { char data; int count; struct dll* next; } dll; typedef struct dictionary { dll * data;
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;
}
}
这是一本字典——不是一本“词典”——一个“n”就足够了!