C中的单个链表

我基本上试图从文本文件创建一个链表,并在每次单词不同时添加一个新成员,如果单词相同,则增加计数(hw赋值)。 我以为我做得对,但似乎无论如何都会增加一个成员。 我想知道我在搜索时是否错误地遍历了列表? 这是我的代码。 有什么想法吗? 谢谢!

LIST *CreateList(FILE *fp) { char input[LINE_LEN]; LIST *root= NULL; /* contains root of list */ size_t strSize; LIST *newList; /* used to allocate new list members */ int same; /* if string is same */ while (fscanf(fp, BUFFMT"s", input) != EOF) { strSize = strlen(input) + 1; if (root == NULL) { if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) { printf("Out of memory..."); exit(EXIT_FAILURE); } if ((newList->str = (char *)malloc(sizeof(strSize))) == NULL) { printf("Not enough memory for %s", input); exit(EXIT_FAILURE); } memcpy(newList->str, input, strSize); /*copy string */ newList->count = START_COUNT; newList->next = NULL; root = newList; } /* if not root node, add node, or increment count */ else { same = ListSame(newList, input); if (same == 1) { root->count++; } else { if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) { printf("Out of memory..."); exit(EXIT_FAILURE); } if ((newList->str = (char *)malloc(sizeof(strSize))) == NULL) { printf("Not enough memory for %s", input); exit(EXIT_FAILURE); } memcpy(newList->str, input, strSize); /*copy string */ newList->count = START_COUNT; newList->next = root->next; root->next = newList; } } } return root; } int ListSame(LIST *head, char *input) { LIST *start = head; for (; start != NULL; start = start->next) { if (strcmp(head->str, input) == 0) { return 1; } } return 0; } 

您正在使用newList调用ListSame ,它始终只有最后创建的节点。 看起来你想将root传递给ListSame。

另外,在ListSame中,它总是检查head-> str,而不是start-> str,这是你的循环变量。

此外,如果ListSame返回true(1),则增加root-> count; 我不确定您是否要增加根节点的计数(计算总重复数)或具有重复的节点的计数(计算每个单词出现的次数)。 如果是后者,则ListSame将需要返回哪个节点是重复的,或者它需要递增计数本身。

此外,您构建列表的方式有点令人困惑。 当你说:

 newList->next = root->next; root->next = newList; 

root-> next在此之前将为NULL或最后创建的节点。 因此,当您在此处执行插入时,您始终将其作为列表中的第二项插入。 这可能不是你想要的。 如果你想追加,你应该跟踪尾巴和头部; 如果你想要前置,只需设置newList->next = root; root = newList; newList->next = root; root = newList;

 LIST *start = head; for (; start != NULL; start = start->next) { if (strcmp(head->str, input) == 0) { return 1; } } 

你应该用吗?

 strcmp(start->str