简体   繁体   English

从文件中读取数字并保存在链表中

[英]Read numbers from file and save in linked list

File Format:文件格式:

7   49
73  58
130 72
144 78
123 9
40  65
92  42
187 3
127 29

I have to read these numbers (has 50 such lines) in the way Xvalue.... Yvalue in the linked list.我必须以 Xvalue.... 链表中的 Yvalue 的方式读取这些数字(有 50 条这样的行)。 I am having trouble reading the numbers.我在阅读数字时遇到问题。 I have created the linked list as follows:我创建了如下链表:

    list L;
    node *p, *q;
    int i;

    L = (list *)malloc(sizeof(node));
    L -> x = L -> y = 0;
    L -> nextx = L -> nexty = NULL;

    FILE *fp;
    fp = fopen("points.txt", "r");
    if (fp == NULL) 
    {
        fprintf(stderr, "Error: unable to open file...\n");
    }

    p = L;
    for (i=0; i<100; ++i) 
    {
        q = (node *)malloc(sizeof(node));
        q -> x =  // store x values here
        q -> y =  // store y values here
        q -> nextx = q -> nexty = NULL;
        p -> nextx = p -> nexty = q;
        p = q;
    }

1) You can use fscanf to read the integer pair from a file. 1)您可以使用fscanf从文件中读取 integer 对。 Check the return value to make sure fscanf matched 2 items检查返回值以确保fscanf匹配 2 个项目

2) Your linked list handling is wrong. 2)您的链表处理错误。 A normal linked list only has one "next" pointer.一个普通的链表只有一个“下一个”指针。

The code can be written in many ways.代码可以用多种方式编写。 Here is one example:这是一个例子:

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

typedef struct s_node
{
    int x;
    int y;
    struct s_node* next;
} node;

void print_list(node* p)
{
    printf("List contains:\n");
    while (p)
    {
        printf("x=%d y=%d\n", p->x, p->y);
        p = p->next;
    }
}

node* new_node(int x, int y)
{
    node* p = malloc(sizeof *p);
    assert(p);
    p->x = x;
    p->y = y;
    p->next = NULL;
    return p;
}

void free_list(node* p)
{
    while(p)
    {
        node* tmp = p;
        p = p->next;
        free(tmp);
    }
}

node* read_list(FILE* fp)
{
    int x, y;
    node* head = NULL;
    node* last = head;

    // Repeat reading as long as fscanf matches 2 items
    while(fscanf(fp, "%d %d", &x, &y) == 2)
    {
        if (last)
        {
            // Insert at end of list
            last->next = new_node(x, y);
            last = last->next;
        }
        else
        {
            // Special handling for first element in list
            head = new_node(x, y);
            last = head;
        }
    }
    return head;    
}

int main(void) 
{
    FILE* fp = stdin;  // Here input is taken from standard in
                       // Use:
                       //        fp = fopen("points.txt", "r");
                       //        assert(fp);
                       //
                       // to read from a file

    node* head = read_list(fp);

    print_list(head);

    free_list(head);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM