合并有序链表

合并有序链表

图解

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

代码如下

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;
	}
}
相关推荐
棱镜Coding13 分钟前
LeetCode-Hot100 27.合并两个有序链表
算法·leetcode·链表
A懿轩A24 分钟前
【2026 最新】Python 与 PyCharm 详细下载安装教程 带图展示(Windows 版)
windows·python·pycharm
求梦82031 分钟前
【力扣hot100题】两两交换链表中的节点(25)
算法·leetcode·链表
Clarice__42 分钟前
Anaconda安装、使用教程
windows·python·机器学习·conda·visual studio code
cong*42 分钟前
搜狗输入法云计算代理导致Windows 10鼠标指针不停转圈的解决方案
windows·计算机外设
血小板要健康43 分钟前
189.轮转数组,力扣
数据结构·算法·leetcode
BackCatK Chen1 小时前
编译 & 运行(Windows)
windows
A懿轩A1 小时前
【2026 最新】Java 与 IntelliJ IDEA 详细下载安装教程 带图演示(Windows 版)
java·windows·intellij-idea
luffy54591 小时前
txt文件所有数据在一列如何转多行多列
windows·excel·txt·一列转多行·一列
无限进步_1 小时前
203. 移除链表元素 - 题解与详细分析
c语言·开发语言·数据结构·git·链表·github·visual studio