链接列表仅打印文本文件行的最后一个单词

时间:2017-12-10 18:37:54

标签: c linked-list

我正在编写一个程序,它接受一个文本文件作为输入,并输出每个单词出现的次数。为此,我使用链接列表,但每当我打印列表时,只打印每行的最后一个单词。下面的代码显示了我如何将每个单词添加到列表中:

while(fgets(line, sizeof(line), fp)) {
    LIST *node = malloc(sizeof(LIST));
    token = strtok(line, delim);

    while (token != NULL) {
        if (search(head, token)) {
            node->count += 1; 
        } else {
            node->string = strdup(token);
            node->count = 1;
            node->next =NULL;
        }

        token = strtok(NULL, delim);
    }

    if (head == NULL) {
        current = head = node;
    } else {
        current = current->next = node;
    }
}

行初始化是:char * line [128];如果单词已经在列表中,则search()返回true,否则返回false,因此如果单词存在,则count递增。    这是我打印的地方:

for (current = head; current ; current = current->next) {
     current->string = strtok(current->string, "\n");
     printf("%-10s | %2d\n", current->string, current->count);
 }

例如,使用文字时:

    mary had a little lamb
    its fleece was white as snow
    and every where that mary went
    the lamb was sure to go

唯一可以打印的单词是lamb,snow,go,go

1 个答案:

答案 0 :(得分:0)

首先检查单词是否已在列表中。如果它在列表中,那么第二次添加它是没有意义的。 search函数应返回LIST*,您可以使用它来增加其值。

同样简化链表如下:

while(fgets(line, sizeof(line), fp)) 
{
    for (char *token = strtok(line, delim); token; token = strtok(NULL, delim))
    {
        int found = 0;
        for(LIST* n = head; n; n = n->next)
            if(strcmp(n->string, token) == 0)
            {
                n->count++;
                found = 1;
            }
        if(found) continue;

        LIST *node = malloc(sizeof(LIST));
        node->next = NULL;
        node->count = 1;
        node->string = strdup(token);
        if(head)
            node->next = head;
        head = node;
    }
}

for(LIST* n = head; n; n = n->next)
    printf("%s, %d\n", n->string, n->count);