合并有序链表

合并有序链表

图解

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

代码如下

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;
	}
}
相关推荐
fish_xk1 小时前
数据结构之二叉树中的堆
数据结构
未名编程2 小时前
Windows 下如何部署 Nacos 并导入配置文件
java·windows
福尔摩斯张2 小时前
Linux进程间通信(IPC)机制深度解析与实践指南
linux·运维·服务器·数据结构·c++·算法
你好~每一天2 小时前
未来3年,最值得拿下的5个AI证书!
数据结构·人工智能·算法·sqlite·hbase·散列表·模拟退火算法
杰克尼2 小时前
3. 分巧克力
java·数据结构·算法
zmzb01033 小时前
C++课后习题训练记录Day39
数据结构·c++·算法
2501_941885963 小时前
智能物流配送优化系统开发与多语言微服务实践:Python、Java、C++与Go全栈实现解析
windows
p***s915 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
在下赵某人5 小时前
概率数据结构的设计原理与误差分析
数据结构·算法·哈希算法
fashion 道格5 小时前
深入理解数据结构中的图:邻接链表的应用与实现
数据结构·链表