【发布时间】:2019-10-21 08:05:57
【问题描述】:
我正在开发一个文字处理器,它被要求能够从单词列表中删除一个单词。
基本上,用户输入单词(因此,字符串),然后将其存储在链表中(这里是dico,这要归功于表示用户输入的所有单词的结构字典)。
不幸的是,我被卡住了:我写的代码似乎只删除了第二个字符,而我希望它能够删除用户请求的单词(这里:str)。
例如,如果用户之前输入了:“hello world”,而他们现在想删除世界“world”,那么 dico 现在应该是“hello”。
typedef struct dll {
char data;
int count; //not needed here
struct dll* next;
} dll; //linked list of each character : dll represents one word
typedef struct dictionary {
dll * data;
struct dictionary* next;
struct dictionary* prev;
} dictionary; //linked list of all the words
dll* entry(){
char data = getc(stdin);
if (data != '\n'){
dll* curr = create_dico(data);
curr->next=entry();
return curr;
}
return NULL;
}
void suppression(dictionary** dico) {
printf("Please enter what you wish to remove out of the list: \n");
dictionary *str = malloc(sizeof(dictionary));
str->data = entry();
str->next = NULL;
dictionary* temp = *dico;
if (str->data == NULL){
*dico = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data->data == str->data->data) {
temp = temp->next;
}
dictionary *next = temp->next->next;
free(temp->next);
temp->next = next;
}
【问题讨论】:
-
与您的问题无关,但请注意
getc返回int值。这样您就可以检查EOF,它表示文件结束或错误。你真的应该检查一下。 -
你需要两个循环,一个循环
dictionary,另一个循环word in dictionary。 -
建议:与其在循环中创建条目,不如在循环中创建条目 (
while(data != \n) { ... })。提示:你需要两个指针,一个指向当前正在创建的列表的头部,一个指向尾部。
标签: c string linked-list