我正在尝试创建一个程序,首先解析一些字符串并将它们添加到链表中,最后打印出每个字符串的出现次数。
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Node Node;
struct Node
{
char* word;
int count;
struct Node *next;
};
Node *head = NULL;
Node *curr = NULL;
Node* listAdd(char* word, bool toEnd) {
Node* tmp = head;
while (tmp) {
if (strcmp(tmp, word) == 0) {
tmp->count++;
return tmp;
}
tmp = tmp->next;
}
printf("allocate memory for node");
Node *ptr = malloc(sizeof(Node));
printf("initialize count to 0");
ptr->count = 0;
printf("allocate memory to hold word");
ptr->word = malloc(strlen(word) + 1);
printf("copy the current word");
strcpy(ptr->word, word);
ptr->next = NULL;
if (toEnd)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
void printList()
{
Node *ptr = head;
while (ptr)
{
printf("\nThe word [%s] has had [%d] occurrences.\n",ptr->word, ptr->count);
ptr = ptr->next;
}
}
char* readWord()
{
static char buffer[100];
scanf("%s", buffer);
printf("listAdd() call");
listAdd(buffer);
return buffer;
}
int main(void)
{
int i = 0;
printf("How many words would you like to type?\n");
scanf("%d", &i);
for (i; i != 0; i--)
{
readWord();
}
printList();
}
当前输出:
How many words would you like to input?
3
hi
bye
yes
How many words would you like to input?
Occurrences: 12086064
任何帮助将不胜感激——我是从C#转向C的新手 :(
searchList
。count
没有被初始化。 - Jacob Seleznevmalloc(sizeof(Node) + strlen(word))
吗? - Sleeplesscount
初始化为 0 并删除第三个ptr->word
,我仍然得到相同的结果。 - Sleepless