将字符串插入链接列表无法正常工作

时间:2016-03-20 08:18:00

标签: c linked-list

我有一个程序应该接受一个输入文件并从中提取字符串并将其添加到链接列表中。我不认为我正确地将字符串添加到链接列表,我似乎无法找到正确的方法。当程序执行时,由于某种原因它会进入无限循环。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct list {
    char *string;
    struct list *next;
};

typedef struct list LIST;

int main() {
    FILE *fp;
    char line[128];
    char file_name[20];
    LIST *current, *head;
    char *p, *s;

    head = current = NULL;
    printf ("Enter the name of the file: ");
    scanf("%s",file_name);

    fp = fopen(file_name, "r");

    while(fgets(line, sizeof(line), fp))
    {
        p = s = line;
        while(*p!=0)
        {
            if (*p==' ')
            {
                LIST *node = malloc(sizeof(LIST));
                *p = 0;
                 node->string = strdup(s);
                 node->next =NULL;

                if(head == NULL){
                current = head = node;
                } else {
                current = current->next = node;
                }
                s = p+1;
            }

            p++;
        }
    }
    fclose(fp);
    //test print
    for(current = head; current ; current=current->next){
        printf("   %s", current->string);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

有几件事:

  • 您对一行中的所有单词使用相同的节点,从而创建node->next等于node的循环。您应该在插入新单词时创建新节点,而不是在读取新行时创建新节点。

  • 你没有抓到一行的最后一个字。您可以利用fgets保留尾随换行符的事实,并检查空格。您还可以考虑使用isspace中的<ctype.h>

    或者,也许更好的是,推迟检查空终止符,直到循环之后。然后,您必须在读取空格或空字符时添加新单词。

  • 当输入文件包含连续的空格或空格字符时,插入空字。您的程序应检查p > s是否仅添加有效单词。 (或者当你以前读过的字符不是空格时,你的程序只能添加有效的单词。)

  • 您为节点和字符串分配内存。在退出程序之前,您应该free这段记忆。

以下是上述修复程序的主循环:

while(fgets(line, sizeof(line), fp))
{
    char *p = line;
    char *s = line;

    do {
        if (*p== ' ' || *p == '\n' || *p == '\t' || *p == '\0') {
            if (p > s) {
                LIST *node = malloc(sizeof(LIST));

                *p = 0;
                node->string = strdup(s);
                node->next = NULL;

                if(head == NULL){
                    head = node;
                } else {
                    current->next = node;
                }
                current = node;
            }
            s = p + 1;
        }

        p++;
    }
    while (*p != 0);
}
相关问题