c++实现两有序链表合并成一个新链表

struct Node
{
	int x;
	Node * next;
	Node(int x1,Node * next1)
	{
		x = x1;
		next = next1;
	}
};

//--两个有序链表合并-假设排列方式为从小到大--
Node * sortHead(Node * head1,Node * head2)
{
	if(head1 == nullptr) return head2; if(head2 == nullptr) return head1;
	Node * returnHead = head1->x<head2->x?head1:head2; //新链表的头节点(里面的是三目运算符..)
	Node * MyPos = returnHead;// 标记新链表的最后一个位置
	if(head1->x < head2->x)
		head1 = head1->next;
	else
		head2 = head2->next;
	while(1)
	{
		if(head1 == nullptr)
		{
			MyPos->next = head2; // head1 都被加载完后另,新链表的最后一个位置与head2串联起来
			break;
		}else if(head2 == nullptr)
		{
			MyPos->next = head1;// 同理--
			break;
		}
		if(head1->x<head2->x)
		{
			MyPos->next = head1;//代码1
			MyPos = head1;//代码2 --作用将目前head1和head2里最小的那个节点放到新链表的最后一个节点-并重新标记新的节点
			head1 = head1->next;
		}else
		{
			MyPos->next = head2;
			MyPos = head2;
			head2 = head2->next;
		}
	}

	return returnHead;
}









  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值