有序链表的归并 分类: 链表 2015-06-07 13:10 11人阅读 评论(0) 收藏

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

TimeLimit: 1000MS Memory limit: 65536K

题目描述

分别输入两个有序的整数序列(分别包含MN个数据),建立两个有序的单链表,将这两个有序单链表合并成为一个大的有序单链表,并依次输出合并后的单链表数据。

输入

第一行输入MN的值;

第二行依次输入M个有序的整数;

第三行依次输入N个有序的整数。

输出

输出合并后的单链表所包含的M+N个有序的整数。

示例输入


65

123 26 45 66 99

1421 28 50 100


示例输出


114 21 23 26 28 45 50 66 99 100

#include <bits/stdc++.h>
#define RR freopen("input.txt","r",stdin)
#define WW freopen("ouput.txt","w",stdout)
using namespace std;
struct node
{
    int data;
    node *next;
};
int main()
{
    int n,m;
    node *head1,*head2,*p,*tail1,*tail2,*q,*r;
    head1=new node;
    head2=new node;
    head1->next=NULL;
    head2->next=NULL;
    tail1=head1;
    tail2=head2;
    cin>>m>>n;
    for(int i=1; i<=m; i++)
    {
        p=new node;
        cin>>p->data;
        p->next=NULL;
        tail1->next=p;
        tail1=p;
    }
    for(int i=1; i<=n; i++)
    {
        p=new node;
        cin>>p->data;
        p->next=NULL;
        tail2->next=p;
        tail2=p;
    }
    p=head2->next;
    while(p)
    {
        r=p->next;
        q=head1->next;
        tail1=head1;
        while(q)
        {
            if(p->data<q->data)
            {
                tail1->next=p;
                p->next=q;
                break;
            }
            else
            {
                q=q->next;
                tail1=tail1->next;
            }
        }
        if(!q)
        {
            tail1->next=p;
            p->next=q;
        }
        p=r;
    }
    p=head1->next;
    while(p)
    {
        if(p!=head1->next)
            cout<<" ";
        cout<<p->data;
        p=p->next;
    }
    cout<<endl;
    return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/juechen/p/4722062.html