1. 程式人生 > 實用技巧 >已有a,b兩個連結串列,每個連結串列中的結點包括學號、成績 要求把兩個連結串列合併, 按學號升序排列

已有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\n", combine->num, combine->grade);
        combine = combine->next;
    }

    return 0;
}

執行截圖: