c-将行读入单链表的最佳方式



我正试图弄清楚如何使用C实现单链表,节点将指针存储到字符串(文件中的行)。我想这不会起作用,因为"line_buffer"会被覆盖,但我看不到任何即时的解决方案。有什么想法吗?

struct line {
    char* string;
    struct line* next;
};
int main(void) {
    ...
    (open file to f)
    ...
    struct line* first = (struct line*) malloc(sizeof(struct line));
    first->string = "string0";
    struct line* current = first;
    char line_buffer[256];
    while (fgets(line_buffer, sizeof(line_buffer), f)) {
        struct line* newl = (struct line*) malloc(sizeof(struct line));
        newl->string = line_buffer;
        current->next = newl;
        current = newl;
        j++;
    }        
    current->next = NULL;
    struct line* temp = first;
    while(temp != NULL) {
        printf("%sn", temp->string);
        temp = temp->next;
    }
}

该输出:

string0
whatever in last line
whatever in last line
whatever in last line

您可以使用strcpy()函数。

代替:

newl->string = line_buffer;

看跌:

strcpy(newl->string, line_buffer);

请注意,这只是对代码进行快速修复的建议,还有更好的方法可以实现此逻辑。

这是伟大的指南

您还可以编写一个简单的insert函数来分离您的逻辑(在列表头插入)

struct line* insertFront(struct line *head, char *string) {
    struct line *newl = malloc(sizeof(struct line));
    newl->string = (char*) malloc(strlen(string)+1);
    if(head == NULL) {           
        strcpy(newl->string, string);
        newl->next = NULL;
        head = newl;
    } else {
        strcpy(newl->string, string);
        newl->next = head;
        head = newl;
    }
    return head;
}

你可以在你的代码中使用这个函数,比如:

int main(void) {
    ...
    (open file to f)
    ...
    struct line* first = NULL;    
    char line_buffer[256];
    while (fgets(line_buffer, sizeof(line_buffer), f)) {
        first = insertFront(first, line_buffer);
    }        
    struct line* temp = first;    
    while(temp != NULL) {
        printf("%sn", temp->string);
        temp = temp->next;
    }
}

相关内容

  • 没有找到相关文章

最新更新