代码实现:
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)///顺序建立链表。
{
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
int t;
while(n--)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&t);
p->data=t;
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
struct node *HB(struct node *head1,struct node *head2)///以head1的头节点当新链表,以特定的排列方式合并两个链表,使新链表有序。
{
struct node *Head,*p1,*p2;
p1=head1->next;
p2=head2->next;
Head=head1;
while(p1&&p2)
{
if(p1->data<=p2->data)
{
Head->next=p1;
Head=p1;
p1=p1->next;
}
else
{
Head->next=p2;
Head=p2;
p2=p2->next;
}
}
if(p1)///如果head1与head2的长度不相等,最后就会有节点剩余,这一步就是将剩余节点出入新链表的后面。
{
Head->next=p1;
}
else
{
Head->next=p2;
}
return head1;
}
void display(struct node *head) ///遍历链表。
{
struct node *q;
q=head->next;
while(q)
{
if(q->next!=NULL)
{
printf("%d ",q->data);
}
else
{
printf("%d\n",q->data);
}
q=q->next;
}
}
int main()
{
struct node *head1,*head2;
int n,m;
scanf("%d%d",&n,&m);
head1=creat(n);
head2=creat(m);
head1=HB(head1,head2);
display(head1);
return 0;
}