数据结构实验之链表四:有序链表的归并

这里写图片描述

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

struct node
{
    int data;
    struct node *next;
};
struct node *h1,*p1,*t1;//完整链表的三要素头指针,移动指针,尾指针
struct node *h2,*p2,*t2;
int main()
{
    int m,n;
    scanf("%d%d",&m,&n);//下面开始建表
    h1=(struct node *)malloc(sizeof(struct node));
    h2=(struct node *)malloc(sizeof(struct node));
    h1->next=NULL;
    h2->next=NULL;
    t1=h1;
    t2=h2;
    while(m--)
    {
        p1=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p1->data);
        p1->next=NULL;
        t1->next=p1;
        t1=p1;
    }
    while(n--)
    {
        p2=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p2->data);
        p2->next=NULL;
        t2->next=p2;
        t2=p2;
    }
    struct node *h,*t,*p;/*这里P可要也可不要,P可用t来代替*/
    h=h1;
    p1=h1->next;
    p2=h2->next;
    free(h2);//表二的头部不要了
    t=h1;//合并表的尾指针一开始指向其头部
    while(p1&&p2)
    {
        if(p1->data>p2->data)/*比较两链表元素大小,谁小谁先插入*/
        {
            t->next=p2;
            t=p2;
            p2=p2->next;
        }
        else
        {
            t->next=p1;
            t=p1;
            p1=p1->next;
        }
        if(p1)t->next=p1;/*最后可能会有一表空一表不空,判断一下找出非空表,直接将非空表后半部分整体插入,跳出循环。*/
        else t->next=p2;
    }
    p=h->next;
    while(p->next)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("%d",p->data);
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值