单链表合并

#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
	int data;
	struct Node *next;
}*STU,nodes; 

STU creat_list(STU head)
{
	STU p1,p;
	int i,num;
	head->next=NULL;
	p1=head;
	printf("请输入要创建的节点个数: \n");
	scanf("%d",&num);
	printf("请输入节点数据: \n");
	for(i=0;i<num;i++)
	{
		p=(STU)malloc(sizeof(nodes));
		scanf("%d",&p->data);
		p1->next=p;
		p1=p;
	}
	p->next=NULL;
	return head;
}

STU Merge(STU head1,STU head2)
{
	STU p1,p2,news,nhead,np;
	nhead=(STU)malloc(sizeof(nodes));
	nhead->next=NULL;
	np=nhead;
	p1=head1->next;
	p2=head2->next;
	while(p1&&p2)
	{
		if(p1->data>p2->data)
		{
			news=(STU)malloc(sizeof(nodes));
			news->data=p2->data;
			
			np->next=news;
			news->next=NULL;
			np=news;
			p2=p2->next;
		} 
		else
		{
			news=(STU)malloc(sizeof(nodes));
			news->data=p1->data;
			np->next=news;
			news->next=NULL;
			np=news;
			p1=p1->next;
		}
		
	}
	while(p1!=NULL)
		{
			news=(STU)malloc(sizeof(nodes));
			news->data=p1->data;
			np->next=news;
			np=news;
			news->next=NULL;
			p1=p1->next;
		}
		while(p2!=NULL)
		{
			news=(STU)malloc(sizeof(nodes));
			news->data=p2->data;
			np->next=news;
			np=news;
			news->next=NULL;
			p2=p2->next;
		}
	printf("合并完成!\n");
	return nhead;
}

void put(STU head)
{
	STU p=head->next;
	
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	
	if(head->next=NULL)
	{
		printf("空链表!\n");
		exit(0);
	}
	
}

int main()
{
	STU head1,head2,news;
	head1=(STU)malloc(sizeof(nodes));
	head2=(STU)malloc(sizeof(nodes));
	creat_list(head1);
	creat_list(head2);
	news=Merge(head1,head2);
	put(news);
	return 0;
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值