您的位置:首页 > 理论基础 > 数据结构算法

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

2016-07-23 09:18 399 查看
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
}*head1,*head2,*tail,*p,*q;
int n1,n2;
struct node * built(int n)
{
struct node *head;
head=(struct node *)malloc(sizeof(struct node));
tail=head;
while(n--)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
tail->next=p;
tail=p;
}
tail->next=NULL;
return head;

}
void print(struct node *head)
{
p=head->next;
while(p)
{
printf("%d",p->data);
if(p->next)
printf(" ");
p=p->next;
}
}
void merger()
{
struct node *p1,*p2;
p1=head1->next;
p2=head2->next;
tail=head1;
while(p1&&p2)
{
if(p1->data<p2->data)
{
tail->next=p1;
tail=p1;
p1=p1->next;
}
else
{
tail->next=p2;
tail=p2;
p2=p2->next;
}
}
if(p1)
tail->next=p1;
else
tail->next=p2;

}
int main()
{
scanf("%d%d",&n1,&n2);
head1=built(n1);
head2=built(n2);
//print(head1);
//print(head2);
//printf("\n");
merger();
print(head1);
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: