有序链表的归并

来源:互联网 发布:html文章发布网页源码 编辑:程序博客网 时间:2024/05/16 23:59

题目描述

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

输入

第一行输入M与N的值; 
第二行依次输入M个有序的整数;
第三行依次输入N个有序的整数。

输出

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

示例输入

6 51 23 26 45 66 9914 21 28 50 100

示例输出

1 14 21 23 26 28 45 50 66 99 100
#include<iostream>
using namespace std;
struct node
{
int data;
struct node* next;
};
int main()
{
struct node *head2,*head1,*tail,*p,*q;
int n,m;
head1=new node;
head1->next=NULL;
tail=head1;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
p=new node;
cin>>p->data;
p->next=NULL;
tail->next=p;
tail=p;
}
head2=new node;
head2->next=NULL;
tail=head2;
for(int i=1;i<=m;i++)
{
q=new node;
cin>>q->data;
q->next=NULL;
tail->next=q;
tail=q;
}
struct node*p1,*q1;
tail=head1;//是设置新链表游动指针,便于插入新结点
p1=head1->next;//是指向第一个链表的第一个结点,用于比较大小
q1=head2->next;//是指向第二个链表的第一个结点,和p比较
while(p1&&q1)
{
if(p1->data<q1->data)
{
tail->next=p1;
tail=p1;
p1=p1->next;
tail->next=NULL;

}
else
{
tail->next=q1;
tail=q1;
q1=q1->next;
tail->next=NULL;
}
}
if(p1)
{tail->next=p1;}
else
{tail->next=q1;}
p=head1->next;
for (int i=0;i<m+n;i++)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return 0;
}
0 0
原创粉丝点击