我正在尝试创建一个程序,该程序首先解析多个字符串并将它们添加到链接列表中,然后以打印出每个字符串的出现次数结束。
\n\n#include<stdio.h>\n#include<stdlib.h>\n#include<stdbool.h>\ntypedef struct Node Node;\n\nstruct Node\n{\n char* word;\n int count;\n struct Node *next;\n};\n\nNode *head = NULL;\nNode *curr = NULL;\n\nNode* listAdd(char* word, bool toEnd) {\n Node* tmp = head;\n while (tmp) {\n if (strcmp(tmp, word) == 0) {\n tmp->count++;\n return tmp;\n }\n tmp = tmp->next;\n }\n printf("allocate memory for node");\n Node *ptr = malloc(sizeof(Node));\n\n printf("initialize count to 0");\n ptr->count = 0;\n\n printf("allocate memory to hold word");\n ptr->word = malloc(strlen(word) + 1);\n\n printf("copy the current word");\n strcpy(ptr->word, word);\n\n ptr->next = NULL;\n\n if (toEnd)\n {\n curr->next = ptr;\n curr = ptr;\n }\n else\n {\n ptr->next = head;\n head = ptr;\n }\n return ptr;\n}\n\nvoid printList()\n{\n Node *ptr = head;\n while (ptr)\n {\n printf("\\nThe word [%s] has had [%d] occurrences.\\n",ptr->word, ptr->count);\n ptr = ptr->next;\n }\n}\n\nchar* readWord()\n{\n static char buffer[100];\n scanf("%s", buffer);\n printf("listAdd() call");\n listAdd(buffer);\n return buffer;\n}\n\nint main(void)\n{\n int i = 0;\n printf("How many words would you like to type?\\n");\n scanf("%d", &i);\n for (i; i != 0; i--)\n {\n readWord();\n }\n printList();\n}\nRun Code Online (Sandbox Code Playgroud)\n\n电流输出:
\n\nHow many words would you like to input?\n3\nhi\nbye\nyes\nHow many words would you like to input?\nOccurrences: 12086064\nRun Code Online (Sandbox Code Playgroud)\n\n任何帮助将不胜感激 \xe2\x80\x94 我仍然是来自 C# 的 C 新手:(
\n您的代码包含一些错误。首先,您将Nodeptr 分配两次:
Node* listAdd(char* word, bool toEnd) {
// ..
Node *ptr = malloc(sizeof(Node));
return ptr;
}
Run Code Online (Sandbox Code Playgroud)
删除语句前面的最后一个return。
您还需要分配内存来保存每个读取的字。现在,每次调用时都会覆盖缓冲区readWord()。然后你会做类似的事情:
Node* listAdd(char* word, bool toEnd) {
// allocate memory for node
Node *ptr = malloc(sizeof(Node));
// initialize count to 0
ptr->count = 0;
// allocate memory to hold word
ptr->word = malloc(strlen(word) + 1);
// copy the current word
strcpy(ptr->word, word);
Run Code Online (Sandbox Code Playgroud)
你的printList()函数需要看起来像这样:
void printList() {
Node* ptr = head;
while(ptr) {
printf("Word: %s %d\n", ptr->word, ptr->count);
ptr = ptr->next;
}
}
Run Code Online (Sandbox Code Playgroud)
由于您从不检查输入的单词是否已存在于列表中,所以每个单词将始终被报告为出现 1 次。这可以这样修复:
// check if the word alreay exists in the list and then increment its count by 1
// this code should go at the top (before allocating ptr) in listAdd()
Node* tmp = head;
while(tmp) {
if(strcmp(tmp->word, word) == 0) {
tmp->count++;
return tmp;
}
tmp = tmp->next;
}
Run Code Online (Sandbox Code Playgroud)
当然,您还应该在退出应用程序之前释放分配的内存:
void freeList() {
Node* ptr = head;
Node* tmp = 0;
while(ptr) {
tmp = ptr->next;
free(ptr->word);
free(ptr);
ptr = tmp;
}
Run Code Online (Sandbox Code Playgroud)