您的位置:首页 > 其它

OJ--链表的归并

2016-04-03 00:00 218 查看


#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)
{int i;
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->next=NULL;
scanf("%d",&p->data);
tail->next=p;
tail=p;
}
return head;
};
struct node * merge(struct node *head1,struct node *head2)
{struct node *p1,*p2,*tail;
p1=head1->next;
p2=head2->next;
free(head2);
tail=head1;
while(p1&&p2)
{
if(p1->data<p2->data)
{
tail->next=p1;
tail=p1;
p1=p1->next;
tail->next=NULL;
}
else
{
tail->next=p2;
tail=p2;
p2=p2->next;
tail->next=NULL;
}
}
if(p1) tail->next=p1;
if(p2) tail->next=p2;
return head1;

};
int main()
{struct node *p,*head1,*head2;
int n,m;
scanf("%d %d",&n,&m);
head1=creat(n);
head2=creat(m);
merge(head1,head2);
p=head1;
while(p->next!=NULL)
{
printf("%d ",p->next->data);
p=p->next;
}

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