C中的单个链表

时间:2010-02-22 08:20:33

标签: c linked-list

我基本上是尝试从文本文件创建链接列表,并在每次单词不同时添加新成员,如果单词相同,则增加计数(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;
}

2 个答案:

答案 0 :(得分:1)

你用newList调用ListSame,newList总是只有最后创建的节点。看起来你想将root传递给ListSame。

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

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

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

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

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

答案 1 :(得分:0)

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

你应该使用

strcmp(start->str