【发布时间】:2011-01-19 13:24:20
【问题描述】:
我基本上是在尝试从文本文件创建一个链接列表,并在每次单词不同时添加一个新成员,如果单词相同则增加计数(硬件分配)。我以为我做得对,但无论如何似乎都添加了一个成员。我想知道我在搜索时是否错误地遍历了列表?这是我的代码。有什么想法吗?谢谢!
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;
}
【问题讨论】:
-
区分大小写吗?如果没有,请尝试使用 stricmp()。
-
如果您使用“关注点分离”,您的代码会更容易理解;即从文件解析代码中提取列表代码...
-
BUFFMT"s"看起来不对。BUFFMT"%s"或许? -
最好的办法是学习如何调试。假设你使用的是 GCC,你可以使用 gdb 来调试:cs.baylor.edu/~donahoo/tools/gdb/tutorial.html,google.com/search?q=how+to+debug+gdb。
-
您是否问过这个问题两次,或者您是否也尝试在 stack overflw 上实现问题的链接编辑列表? :) stackoverflow.com/questions/2309359/…
标签: c linked-list