读入单链表的最佳方法

时间:2014-09-16 01:21:12

标签: c linked-list

我试图弄清楚如何使用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("%s\n", temp->string);
        temp = temp->next;
    }
}

输出:

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

1 个答案:

答案 0 :(得分:0)

您可以使用strcpy()功能。

而不是:

newl->string = line_buffer;

把:

strcpy(newl->string, line_buffer);

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

这是great guide

此外,您可以编写一个简单的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("%s\n", temp->string);
        temp = temp->next;
    }
}