两个递增有序的链表,运用指针实现链表合并成递减链表

#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 ;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值