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

sdut.acm2012级《程序设计基础Ⅱ)》_链表 数据结构实验之链表四:有序链表的归并

2013-05-11 21:30 435 查看


#include <stdio.h>
#include <malloc.h>
struct node
{
int inum;
struct node *next;
};
struct node *create1(int NUM1)
{
struct node *head,*tail,*p;
int i;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
tail = head;
for(i =1;i <= NUM1;i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->next = NULL;
scanf("%d",&p->inum);
tail->next = p;
tail = p;
}

return (head);
}
struct node *create2(int NUM2)
{
struct node *head,*tail,*p;
int i;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
tail = head;
for(i =1;i <= NUM2; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->next = NULL;
scanf("%d",&p->inum);
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;
tail = head1;
free( head2 );
while(p1&&p2)
if(p1->inum < p2->inum)
{
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;
}
return (head1);

}
void print(struct node *head,int SUM)
{
struct node *p;
int i;
p = head->next;

for(i = 1;i < SUM;i++)
{
printf("%d ",p->inum);
p = p->next;
}
printf("%d\n",p->inum);
}
int main()
{
struct node *Head1,*Head2;
int num1,num2,sum;
scanf("%d %d",&num1,&num2);
sum = num1 + num2;
Head1 = create1(num1);
Head2 = create2(num2);
Head1 = Merge(Head1,Head2);
print(Head1,sum);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: