#include <stdio.h>
#include <stdlib.h>
struct Zeng
{
int data;
struct Zeng *next;
};
struct Zeng *Create();
void Shu(struct Zeng *head);
struct Zeng *He(struct Zeng *head1,struct Zeng *head2);
int main()
{
struct Zeng *Z1,*Z2,*Z;
printf("请输入链表Z1的元素(从小到大输入,输入-1回车结束):\n");
Z1=Create();
printf("请输入链表Z2的元素(从小到大输入,输入-1回车结束):\n");
Z2=Create();
printf("链表创建结果如下:\n");
Shu(Z1);
Shu(Z2); //测试链表是否创建成功
Z=He(Z1,Z2); //合并递增链表为递减链表
Shu(Z);
return 0;
}
struct Zeng *Create()
{
struct Zeng *head=NULL,*p,*p1;
p=(struct Zeng *)malloc(sizeof(struct Zeng));
scanf("%d",&p->data );
p->next =NULL;
while(p->data !=-1)
{
if(head==NULL)
{
head=p;
p1=p;
}
else
{
p1->next =p;
p1=p;
}
p=(struct Zeng *)malloc(sizeof(struct Zeng));
scanf("%d",&p->data );
p->next =NULL;
}
return head;
}
void Shu(struct Zeng *head)
{
struct Zeng *p;
p=head;
while(p!=NULL)
{
printf("%-3d",p->data );
p=p->next ;
}
putchar('\n');
}
struct Zeng *He(struct Zeng *head1,struct Zeng *head2)
{
struct Zeng *head,*p1,*p2,*temp;
p1=head1;
p2=head2;
head=(struct Zeng *)malloc(sizeof(struct Zeng)); //创建头节点,方便实现头插法
head->next =NULL;
while(p1!=NULL&&p2!=NULL) //因为两个链表是递增,要合并变成递减可以考虑头插法
{
if(p1->data <p2->data ) //每次将两个链表当前结点值进行比较,插入最小的结点
{
temp=p1; //取出结点
p1=p1->next ; //p1链表指向下一个结点
}
else
{
temp=p2; //取出结点
p2=p2->next ; //p2链表指向下一个结点
}
if(head->next ==NULL) //插入新链表
{
head->next =temp;
head->next->next =NULL; //头插法,所以要收尾
}
else
{
temp->next =head->next ;
head->next =temp;
}
}
if(p1!=NULL) //假设还有一个链表有元素,或者最开始就有一个链表为空
while(p1!=NULL)
{
temp=p1;
p1=p1->next ;
if(head->next ==NULL)
{
head->next =temp;
head->next->next =NULL; //头插法,所以要收尾
}
else
{
temp->next =head->next ;
head->next =temp;
}
}
if(p2!=NULL)
while(p2!=NULL)
{
temp=p2;
p2=p2->next ;
if(head->next ==NULL)
{
head->next =temp;
head->next->next =NULL;
}
else
{
temp->next =head->next ;
head->next =temp;
}
}
return head->next ;
}
05-10
6440
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交