合并有序链表

合并有序链表

图解

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

代码如下

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;
	}
}
相关推荐
Mr_hwt_1231 小时前
Windows安装Claude Code详细教程(含apikey配置)
windows·ai编程·claude code
Zhang~Ling1 小时前
深入解析C++list:从0到1实现一个完整的链表类
c++·链表·list
Languorous.2 小时前
Windows 安装 Linux 虚拟机 / WSL 完整教程(新手零失败)
linux·运维·windows
郭龙飞9802 小时前
OpenClaw技能拓展教程 五大场景高效办公实操指南
人工智能·windows·语言模型
小鹿软件办公3 小时前
在 Windows 中什么是 iphlpsvc?禁用它安全吗?
windows·安全·iphlpsvc
诸神缄默不语3 小时前
DNS 与 hosts 文件:Windows 11 中的名称解析配置
windows·计算机网络·dns·hosts
smj2302_796826524 小时前
解决leetcode第3934题最短唯一子数组
数据结构·python·算法·leetcode
iiiiyu4 小时前
面向对象和集合编程题
java·开发语言·前端·数据结构·算法·编程语言
变量未定义~4 小时前
最长回文子串
数据结构·算法
牙牙要健康4 小时前
Windows 下为 VSCode 配置 Anaconda:从零安装 Python 环境到完整配置教程
windows·vscode·python