合并排序的两个链表

题目:输入两个递增排序的链表,合并这两个链表并使新链表的节点仍然是递增排序的

方法一:递归实现

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
	if(pHead1==nullptr)
		return pHead2;
	if(pHead2==nullptr)
		return pHead1;
	ListNode* head=nullptr;
	if(pHead1->val < pHead2->val)
	{
		head=pHead1;
		head->next=Merge(pHead1->next, pHead2);
	}
	else
	{
		head=pHead2;
		head->next=Merge(pHead1, pHead2->next);
	}
	return head;
}

方法二:非递归实现

Node *ListMerge(Node *head1,Node *head2)
{
	if(!head1) return head2;
	if(!head2) return head1;
	Node *head=NULL;//合并后的头指针
	Node *p1=head1;//p1用于扫描链表1
	Node *p2=head2;//p2用于扫描链表2
	if(head1->value<head2->value)
	{
		head=head1;
		p1=head1->next;
	}
	else
	{
		head=head2;
		p2=head2->next;
	}
	Node *p=head;//p永远指向最新合并的结点
	while(p1 && p2)//如果循环停止,则p1或p2至少有一个为NULL
	{
		if(p1->value<p2->value)
		{
			p->next=p1;
			p1=p1->next;
		}
		else
		{
			p->next=p2;
			p2=p2->next;
		}
		p=p->next;
	}
	if(p1)//如果链1还没走完
	{
		p->next=p1;
	}
	else if(p2)//如果链2还没走完
	{
		p->next=p2;
	}
	return head;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值