【问题标题】:Reading a file containing student names and ages and displaying them in sorted order读取包含学生姓名和年龄的文件并按排序顺序显示它们
【发布时间】:2020-11-09 14:39:58
【问题描述】:

当我运行这个程序时,它只打印到“I”而不是一直到“Z”的名称。我尝试先读取文件并将其内容存储到链接列表中,然后按排序顺序显示内容。下面是程序正在读取的文件和程序本身。请帮忙。

文件:

萨米尔 20

奥雅纳 18

内哈 22

阿西姆 19

伊萨克 21

计划:

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

int main()
{
    FILE *fp;

    struct student
    {
        char name[20];
        int age;
        struct student *pre, *next;
    };
    struct student *s, *f;
    s = (struct student *)malloc(sizeof(struct student));
    s->pre = NULL;
    s->next = NULL;
    f = s;

    fp = fopen("A.txt", "r");
    if(fp == NULL)
    {
        printf("Not Opened");
        exit(0);
    }

    while(1)
    {
        if(fscanf(fp, "%s %d", s->name, &s->age) == EOF)
        {
            s = s->pre;
            s->next = NULL;
            break;
        }
        else
        {
           s->next = (struct student *)malloc(sizeof(struct student));
           s->next->pre = s;
           s->next->next = NULL;
           s = s->next;
        }
    }

    s = f;

    char ch = 'A';

    while(1)
    {
        if(ch == 'Z'+1)
            break;

        while(1)
        {
            if(f->name[0] == ch)
            {
                printf("%s %d\n", f->name, f->age);
                f->next->pre = f->pre;
                f->pre->next = f->next;
                if(f->next == NULL)
                    break;
                else
                    f = f->next;
            }

            if(f->next == NULL)
                break;
            else
                f = f->next;
        }

        ch = ch +1;
        f = s;
    }

    fclose(fp);
}

【问题讨论】:

    标签: c file sorting linked-list


    【解决方案1】:

    问题在于以下几行:

    f->next->pre = f->pre;
    f->pre->next = f->next;
    

    如果您删除这些,则列表打印得很好。但是,仅对打印进行排序,而不是列表。如果您想订购列表,请参阅:

    Sort a Linked list using C

    【讨论】:

    • 嗯,但是为什么这两行会导致打印出现问题?
    • 因为要重新排序任何东西,您需要一个临时缓冲区 tmp。那么如果你想交换元素a和b,你必须这样做:tmp​​ = a, a = b, b = tmp。你这里没有遵循这个原则。
    • @AbhirupBakshi 如果我的回答涵盖了您的问题,您可以接受它以关闭此帖子。
    【解决方案2】:

    您似乎混合了两个概念:排序和打印。

    if(f-&gt;name[0] == ch) 然后打印它并重新链接列表。我不知道你为什么重新链接它,我也没有检查你是否对它进行排序(我觉得不是)。

    要么首先对列表进行排序(例如实现气泡或使用快速排序)然后打印它,或者像现在一样打印列表但删除重新链接(然后它会打印得很好 - 除了AB可以在AA 之前打印,因为您只检查第一个字母)。

    【讨论】:

      猜你喜欢
      • 2016-08-31
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2012-08-10
      相关资源
      最近更新 更多