链表合并

已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序

#include <stdio.h>
#include <iostream>
using namespace std;

//已知有两个有序链表head1,head1,将它们合并成一个新的有序链表
typedef struct Node
{
	int data;
	struct Node *next;
}NODE;

NODE* Merge(NODE *head1,NODE *head2)
{
	//若链表head1为空,返回head2
	if(head1==NULL)
	{
		return head2;
	}
	//若链表head2为空,返回head1
	if(head2==NULL)
	{
		return head1;
	}
	NODE *head = NULL;
	NODE *p1 = NULL;
	NODE *p2 = NULL;
	//将数据最小的链表头给head,引入p1,p2进行指针的向后移动
	if(head1->data <= head2->data)
	{
		head = head1;		
		p1 = head1->next;
		p2 = head2;
	}
	else
	{
		head = head2;
		p1 = head1;
		p2 = head2->next;
	}
	NODE *pc = head; //current node
	while(p1!=NULL && p2!=NULL)
	{
		if(p1->data <= p2->data)
		{
			pc->next=p1;
			pc  = p1;
			p1 = p1->next;			
		}
		else
		{
			pc->next = p2;
			pc = p2;
			p2 = p2->next;
		}
	}
	if(p1!=NULL)
	{
		pc->next = p1;
	}
	else if(p2!=NULL)
	{
		pc->next=p2;
	}
	return head;
}
//链表的创建
NODE* Create(NODE p[],int n)
{
	NODE *head = &p[0];
	for(int i=0;i<n-1;i++)
	{
		p[i].next = &p[i+1];
	}
	p[n-1].next = NULL;
	return head;
}
//链表的输出
void output(NODE *head)
{
	NODE *p = head;
	int i = 0;
	while(p!=NULL)
	{
		printf("%d\t",p->data);
		p = p->next;
		if(++i%5==0)
		{
			printf("\n");
		}
	}
}

int main()  
{  
	
	NODE a[10] = {{1},{3},{4},{6},{8},{12},{15},{17},{19},{23}};
	NODE b[5] ={{4},{5},{7},{10},{18}};
	NODE *head1 = Create(a,10);
	NODE *head2 = Create(b,5);
	printf("原始链表head1是:\n");
	output(head1);
	printf("\n原始链表head2是:\n");
	output(head2);
	NODE *head =Merge(head1,head2);
	printf("\n合并后的链表head是:\n");
	output(head);
	system("pause");  
	return 0;  
}  

输出结果:


//递归
NODE* MergeRec(NODE *head1,NODE *head2)
{
	//若链表head1为空,返回head2
	if(head1==NULL)
	{
		return head2;
	}
	//若链表head2为空,返回head1
	if(head2==NULL)
	{
		return head1;
	}
	NODE *head = NULL;
	if(head1->data<=head2->data)
	{
		head = head1;
		head->next = MergeRec(head1->next,head2);
	}
	else
	{
		head = head2;
		head->next = MergeRec(head1,head2->next); 
	}
	return head;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值