两个链表合并到新的链表里面


#include<stdio.h>
#include<stdlib.h>
typedef struct node* List;
struct node{
	int data;
	List next;
};

//从终端输入链表大小和的数据
List ReadList()
{
	List L,t,head;
	int data,N;
	head = (List)malloc(sizeof(struct node));
	if(head == NULL)
	{
		printf("No enough to mallocate!\n");
		exit(0);
	}
	t = head;
	scanf("%d",&N);
	while(N--)
	{
		L = (List)malloc(sizeof(struct node));
		scanf("%d",&data);
		L->data = data;
		t->next = L;
		t = L;
	}
	t->next = NULL;
	
	return head;
}

/*List ReadList()
{
	List L,t,head;
	int N;
	head = (List)malloc(sizeof(struct node));
	head->next = NULL;
	t = head;
	scanf("%d",&N);
	while(N--)
	{
		L = (List)malloc(sizeof(struct node));
		scanf("%d",&(L->data));
		L->next = t->next;
		t->next = L;
		t=L;
	}
	return head;
}*/

//合并两个链表到新的链表里面
List MergeAB(List ha,List hb)
{
 List t1,t2,t3,hc;
 hc = ha;
 t1 = ha->next;
 t2 = hb->next;
 t3 =hc;
 while(t1&&t2)
 {
 	if(t1->data<t2->data)
 	{
 		t3->next = t1;
 		t1 = t1->next;
 		t3 = t3->next;
	 }
	 else
	 {
	 	t3->next = t2;
	 	t2 = t2->next;
	 	t2 = t3->next;
	 }
	 while(t1)
	 {
	 	t3->next = t1;
	 }
	 while(t2)
	 {
	 	t3->next = t2;
	 }	 
 }
	return hc;
}


void PrintHc(List hc)
{
	List t;
	t = hc->next;
    int flag=0;
    if(hc==NULL)
    {
    	printf("NULL");
	}
	while(hc!=NULL)
	{
		if(flag)
		{
			printf(" ");
		}
		else
		{
			flag = 1;
			printf("%d",hc->data);
			hc = hc->next;
		}
	}
}

int main(void)
{
	List ha,hb,hc;
    //输入要合并的链表
	ha = ReadList();
	hb = ReadList();
    //将两个链表合并在新的链表,按大小顺序合并
	hc =  MergeAB(ha,hb);
	PrintHc(hc);
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值