有序单链表的合并:递归和非递归方法

已知有两个有序的单链表head1和head2。分别使用递归方法和非递归的方法合并成一个有序的单链表。

1:递归方法。

假设两个链表:1->3->5;2->4->6.
递归的步骤如下:
(1) 比较链表一和链表2的第一个数据节点,由于1<2,因此将结果链表中的表头节点指向链表1中的第一个节点,即数据1所在节点。

(2) 对剩余的链表1和链表2再调用(1)过程,比较得到结果链表的第2个节点,即2与3比较得到2。此时合并的链表节点为1->2.
(3) 递归直到两个链表的节点都被加到结果链表中。

实现的主要函数:

Node *MergeRecursive(Node *head1,Node *head2)
{
	Node *head=NULL;
	if(head1==NULL)
		return head2;
	if(head2==NULL)
		return head1;

	if(head1->data < head2->data)
	{
		head=head1;
		head->next=MergeRecursive(head1->next,head2);
	}	
	else
	{
		head=head2;
		head->next=MergeRecursive(head1,head2->next);
	}
	return head;
}

2:非递归方法。

选取两个链表中长度最短的一个链表,将最短的链表中的元素一次插入到最长链表中即可。

Node* Insert_node(Node* head,Node* item)
{
	Node *p=head;
	Node *q=NULL;//始终指向p之前的节点
	while(p->data < item->data && p!=NULL)
	{
		q=p;
		p=p->next;
	}

	if(p==head)//item->data<p-data;//插入到原头结点之前
	{
		item->next=p;
		return item;
	}

	q->next=item;//插入到q与p之间
	item->next=p;
	return head;
}

int length(Node *head)
{
	Node *p=head->next;
	int len=0;

	if(head->next==NULL)
		return 0;
	while(p!=NULL)
	{
		len++;
		p=p->next;
	}
	return len;
}

Node *merge(Node *head1,Node *head2)
{
	Node *head=NULL;//合并后的头指针;
	Node *p=NULL;
	Node *nextP=NULL;//指向p之后

	if(head1==NULL)
		return head2;
	if(head2==NULL)
		return head1;

	if(length(head1) > length(head2))//选取较短的链表
	{
		head=head1;
		p=head2;
	}
	else if(length(head1) == length(head2))
	{
		head=head2;
		p=head1;
	}
	else
	{
		head=head2;
		p=head1;
	}
	while(p!=NULL)
	{
		nextP=p->next;
		head=Insert_node(head,p);
		p=nextP;
	}
	return head;
}

下面是非递归方法的测试程序:

int main()
{
	Node *head1=NULL,*head2=NULL;
	Node *head=NULL;

	cout<<"create 1th list : "<<endl;
	head1=create();
	cout<<"create 2th list : "<<endl;
	head2=create();
	
	cout<<"print the data of 1th list is: "<<endl;
	print (head1);
	cout<<endl;
	cout<<"print the data of 2th list is: "<<endl;
	print (head2);
	cout<<endl;

	cout<<"print the data of Merge list is: "<<endl;
//	head=MergeRecursive(head1,head2);//递归法合并两个链表
	head=merge(head1,head2);//非递归方法合并两个链表
	print(head->next);

return 0;
}

输出结果如下:



采用递归的方法,输出结果与上面的一样,,此处就不在加以说明。

实现有序单链表的合并,完整代码git@code.csdn.net:snippets/2431552.git或者https://code.csdn.net/snippets/2431552.git


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C-Jonn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值