YTU-OJ-单链表(线性表)-合并两个升序链表后降序输出

问题及代码:
/*   
*Copyright (c)2015,烟台大学计算机与控制工程学院   
*All rights reserved.   
*文件名称:score.cpp   
*作    者:单昕昕   
*完成日期:2015年3月20日   
*版 本 号:v1.0   
*   
*问题描述:合并两个升序链表后降序输出。 
*程序输入:两个升序链表。
*程序输出:降序链表中的数据。  
*/ 
#include<stdio.h>
#include<stdlib.h>
struct stud/*定义链表*/
{
    int data;
    struct stud *next;
};
void sort(struct stud *head3,int count1,int count2)/*冒泡排序法*/
{
    int i,temp=0;
    struct stud *p;

    for(i=0; i<count1+count2-2; ++i)
        for(p=head3->next; p->next!=NULL; p=p->next) /*对链表1进行排序*/
        {
            if(p->data<p->next->data)
            {
                temp=p->data;
                p->data=p->next->data;
                p->next->data=temp;
            }
        }
    p=head3->next;
    while(p)
    {
        printf("%d",p->data);
        printf(" ");
        p=p->next;
    }
}
int main()
{
    struct stud *head1,*head2,*p,*q,*head3;
    int count1=1,count2=1,m,n;
    head3=(struct stud *)malloc(sizeof(struct stud *));/*定义链表头结点,并分配空间*/
    head3->next=NULL;
    head1=(struct stud *)malloc(sizeof(struct stud *));
    head2=(struct stud *)malloc(sizeof(struct stud *));
    p=(struct stud *)malloc(sizeof(struct stud *));
    q=(struct stud *)malloc(sizeof(struct stud *));
    head1->next=NULL;
    head2->next=NULL;
    scanf("%d",&m);
    while(m>0)/*链表1输入数据*/
    {
        scanf("%d",&p->data);
        count1++;
        p->next=head1->next;
        head1->next=p;
        p=(struct stud *)malloc(sizeof(struct stud *));
        m--;
    }
    scanf("%d",&n);
    while(n>0)/*链表2输入数据*/
    {
        scanf("%d",&q->data);
        count2++;
        q->next=head2->next;
        head2->next=q;
        q=(struct stud *)malloc(sizeof(struct stud *));
        n--;
    }
    head1=head1->next;
    head2=head2->next;
    while(head1!=NULL&&head2!=NULL)/*将排序好的链表1和2 的数据导入链表3*/
    {
        if(head1->data<=head2->data)
        {
            p=head1->next;

            head1->next=head3->next;
            head3->next=head1;

            head1=p;
        }
        else
        {
            q=head2->next;

            head2->next=head3->next;
            head3->next=head2;

            head2=q;
        }
    }
    if(head1!=NULL)/*如果有链表1或2的数据不为空,将剩下的数据导入链表3中*/
    {
        p=head1;
        while(p!=NULL)
        {
            q=p->next;
            p->next=head3->next;
            head3->next=p;
            p=q;
        }
    }
    if(head2!=NULL)
    {
        q=head2;
        while(q!=NULL)
        {
            p=q->next;
            q->next=head3->next;
            head3->next=q;
            q=p;
        }
    }
    sort(head3,count1,count2);
}


运行结果:


知识点总结:
合并两个升序链表后降序输出。

学习心得:

将两个线性表保存到一个新的表中,然后用冒泡排序法降序排列后输出。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值