考上研究僧 2022-01-23 00:48 采纳率: 97.4%
浏览 13
已结题

两个链表的排序问题,如何解决?

题:将a,b两个链表连接起来并按升序排列。


#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct Student)
struct Student
{
    long num;
    int score;
    struct Student* next;
};
int main()
{
    struct Student* Creat_List(void);
    struct Student* Insert(struct Student* ahead, struct Student* bhead);
    void Print(struct Student* ahead);
    struct Student* ahead, * bhead, * abhead;
    printf("list a:\n");
    ahead = Creat_List();
    printf("list b:\n");
    bhead = Creat_List();
    abhead = Insert(ahead, bhead);
    Print(abhead);
    return 0;
}
struct Student* Creat_List(void)
{
    int n = 0;
    struct Student* p1, * p2, * head=NULL;
    p1 = p2 = (struct Student*)malloc(LEN);
    scanf_s("%ld %d", &p1->num, &p1->score);
    while (p1->num != 0)
    {
        n = n + 1;
        if (n == 1)
            head = p1;
        else
            p2->next = p1;
        p2 = p1;
        p1 = (struct Student*)malloc(LEN);
        scanf_s("%ld %d", &p1->num, &p1->score);
    }
    p2->next = NULL;
    return head;
}
struct Student* Insert(struct Student* ahead, struct Student* bhead)
{
    struct Student* pa1, * pa2, * pb1, * pb2;
    pa1 = pa2 = ahead;
    pb1 = pb2 = bhead;
    do
    {
        while ((pa1->num < pb1->num) && (pa1->next != NULL))
        {
            pa2 = pa1;
            pa1 = pa1->next;
        }
        if (pa1->num >= pb1->num)
        {
            if (pa1 == ahead)
                ahead = pb1;
            else
                pb2->next = pb1;
            pb1 = pb1->next;
            pb2->next = pa1;
            pa2 = pb2;
            pb2 = pb1;
        }
    } while ((pa1->next != NULL) || (pa1 == NULL && pb1 != NULL));
    if ((pb1 != NULL) && (pb1->num > pa1->num) && (pa1->next == NULL))
        pa1->next = pb1;
    return ahead;
}
void Print(struct Student* ahead)
{
    struct Student* p;
    p = ahead;
    while (p != NULL)
    {
        printf("%ld %d\n", p->num, p->score);
        p = p->next;
    }
}

结果为什么这样了?

img


另外:有无hxd梳理一下它这个Insert函数的思路,大脑有点混乱。尤其没明白那个do.while.循环条件。

  • 写回答

1条回答 默认 最新

  • Hann Yang 全栈领域优质创作者 2022-01-23 07:06
    关注

    将a,b两个链表连接起来,【并按升序排列】
    不仅是插入,而是两个链表接元素的大小交替合并
    并且:
    a,b本身也是升序链表,否则Insert()也完成不任务的

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 2月1日
  • 已采纳回答 1月24日
  • 创建了问题 1月23日

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势