gpt4 book ai didi

c - 在单链表中插入字符串

转载 作者:行者123 更新时间:2023-11-30 14:35:31 25 4
gpt4 key购买 nike

我正在尝试将一个字符串插入到其他字符串的链接列表中。目标是让用户输入他们想要的任何字符串(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;
}
}

关于c - 在单链表中插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com