合并有序链表

合并有序链表

图解

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

代码如下

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;
	}
}
相关推荐
JasmineX-14 分钟前
数据结构(笔记)——顺序栈
c语言·数据结构·笔记
2601_9496955930 分钟前
3DM游戏运行库合集安装教程,缺少DLL文件这样修复
windows·游戏·电脑
凉茶钱2 小时前
list:哨兵节点,const_iterator 和 const iterator的区别与迭代器失效
数据结构·c++·list
Nontee2 小时前
Quartz 新手入门:定时任务的两个承诺
开发语言·windows·python
weixin_437961922 小时前
Docker安装(windows)
windows·docker·容器
kyle~2 小时前
Windows 多 AP 同名 Wi-Fi 网络异常问题复盘
网络·windows
持敬chijing3 小时前
白盒测试与代码审计-Claude Code Windows环境搭建
windows·安全·网络安全·网络攻击模型
敲代码的苦133 小时前
头歌数据结构-排序的实现及其应用
数据结构
有同事要进步4 小时前
Leecode第68题:x的平方根
java·数据结构·算法
Pniubi4 小时前
HashMap扩容全流程
java·开发语言·数据结构