zoukankan      html  css  js  c++  java
  • 已有a,b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并, 按学号升序排列

    已有a,b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并, 按学号升序排列。

    解题思路:

    首先合并两个链表,然后采用选择排序,给合并之后的链表进行排序。

    #include <stdio.h>
    typedef struct student
    {
        int num;
        double grade;
        struct student *next;
    } student;
    
    student *merge(student *a, student *b)
    {
        //先合并,后排序
        student *head = a;
        while (a->next != NULL)
        {
            a = a->next;
        }
        a->next = b;
    	//选择排序,每次选最小的,放在未排序的链表头部
        student *pre;
        pre = head;
        while (pre->next != NULL)
        {
            a = pre->next;
            while (a != NULL)
            {
                if (pre->num > a->num)
                {
                    int num = pre->num;
                    double grade = pre->grade;
                    pre->num = a->num;
                    pre->grade = a->grade;
                    a->num = num;
                    a->grade = grade;
                }
                a = a->next;
            }
            pre = pre->next;
        }
        return head;
    }
    int main()
    {
        student a[3] = {{1, 79}, {4, 36}, {5, 79}};
        for (int i = 0; i < 2; i++)
        {
            a[i].next = &a[i + 1];
        }
    
        student b[2] = {{2, 38}, {6, 98}};
        for (int i = 0; i < 1; i++)
        {
            b[i].next = &b[i + 1];
        }
        student *combine = merge(a, b);
        while (combine != NULL)
        {
            printf("%d -> %.2lf
    ", combine->num, combine->grade);
            combine = combine->next;
        }
    
        return 0;
    }
    

    运行截图:
    已有a,b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并, 按学号升序排列

  • 相关阅读:
    css水平垂直居中
    JavaScript提供了哪几种“异步模式”?
    sort()
    后端开发中,可以在Cache-Control设置的常用指令
    纯函数
    react和vue
    npm(classnames) 更灵活使用类名
    shell知多少?
    常见的HTTP状态码
    axios
  • 原文地址:https://www.cnblogs.com/weiyidedaan/p/13331338.html
Copyright © 2011-2022 走看看