合并有序链表

合并有序链表

图解

虽然很复杂,但能够很好的理解怎么使用链表,以及对链表的指针类理解

代码如下

cpp 复制代码
Node* merge_list_two_pointer(List& list1, List& list2)
{
	Node* new_head1 = list1.head;
	Node* new_head2 = list2.head;
	Node* sentinel1 = list1.head;
	Node* sentinel2 = list2.head;
	Node* temp_head1 = NULL;
	Node* temp_head2 = NULL;
	int flage = 1;
	//因为下面是<=,所以以list2优先为空
	if (new_head1->data >= new_head2->data)
	{
		flage = 2;
	}
	while (new_head1 != NULL && new_head2 != NULL)
	{
		while (list1.head != NULL && list1.head->data < list2.head->data)
		{
			temp_head1 = list1.head;
			list1.head = list1.head->next;
		}
		//正常两个有序列表,上面为空,
		//456,123456789
		if (list1.head == NULL && flage == 2)
		{
			temp_head1->next = list2.head;
			return sentinel2;
		}
		//特殊情况列表,全大
		//123,456
		if (list1.head == NULL)
		{
			temp_head1->next = new_head2;
			return sentinel1;
		}
		if (temp_head1 != NULL)
		{
			temp_head1->next = new_head2;
		}

		while (list2.head != NULL && list2.head->data <= list1.head->data)
		{
			temp_head2 = list2.head;
			list2.head = list2.head->next;
		}
		//正常两个有序列表,下面为空
		//123456789,456
		if (list2.head == NULL && flage == 1)
		{
			temp_head2->next = list2.head;
			return sentinel1;
		}
		//特殊情况列表也就是,全小
		//456,123
		if (list2.head == NULL)
		{
			//防止89,89这种类型链表跑空
			temp_head2->next = list1.head;
			return sentinel2;
		}
		//这里不需要判断这个为空。如果为空,则说明已经到达链表尾部
		temp_head2->next = list1.head;

		new_head1 = list1.head;
		new_head2 = list2.head;
	}
}
相关推荐
小羊没烦恼!11 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
rockmelodies11 小时前
# Windows Server2008 R2 Standard(SP1镜像U盘)重置本地管理员密码【完整详细步骤】
windows·密码破解
m0_5474866613 小时前
《数据结构教程》全套 PPT课件2026
数据结构
kakakahahahaha18 小时前
Windows C盘空间不足的安全清理与迁移流程
windows·电脑·笔记本电脑·软件需求·c盘清理
做咩啊~18 小时前
远程连接提示:身份验证错误,要求的函数不受支持
windows
tryxr18 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_318 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.19 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
百事牛科技19 小时前
PPT只读怎么取消?四种情况分别处理
windows·powerpoint
All for pursuit.19 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode