合并两个有序链表,合并之后仍有序

合并两个有序链表,合并之后仍有序。

头文件引用链表的一些基本操作
ListNode * MergeOrderedList(ListNode *List1,ListNode *List2)
{
	ListNode *cur1 = List1;
	ListNode *cur2 = List2;
	ListNode *result = NULL;
	ListNode *tail = NULL;
	ListNode *next;
	
	while(cur1 != NULL && cur2 != NULL)
	{
		//取链表1的结点
		if(cur1->data <=cur2->data)
		{
			//结果链表不为空,直接在最后一个结点做插入
			if(result !=NULL)  
			{
				//保存下一个结点,方便循环
				next = cur1->next;

				//插入过程
				tail->next = cur1;
				cur1->next = NULL;
				//保存新的最后一个结点
				tail = cur1;

				cur1 = next;
			}
			//结果链表为空
			else
			{
				next = cur1->next;
				result = cur1;
				cur1->next = NULL;
				tail = cur1;
				cur1 = next;
			}
		}
		//取链表2的结点
		else
		{
			if(result != NULL)
			{
				next = cur2->next;
				tail->next = cur2;
				cur2->next = NULL;
				tail = cur2;
				cur2 = next;
			}
			else
			{
				next = cur2->next;
				result = cur2;
				cur2->next = NULL;
				tail = cur2;
				cur2 = next;
			}
		}
	}

	//一个链表为空的情况
	if(cur1 == NULL)
	{
		tail->next = cur2;
	}
	if(cur2 == NULL)
	{
		tail->next = cur1;
	}
	return result;
}

void ListPrint(ListNode *first)
{
	for(ListNode *cur = first;cur!=NULL;cur = cur->next)
	{
		printf("%d-> ",cur->data);
	}
	printf("NULL\n");
}
void TestMerge()
{
	ListNode *List1 = NULL;
	ListNode *List2 = NULL;

	ListPushBack(&List1,1);
	ListPushBack(&List1,1);
	ListPushBack(&List1,3);
	ListPushBack(&List1,4);
	ListPushBack(&List1,6);
	ListPushBack(&List1,7);

	ListPushBack(&List2,1);
	ListPushBack(&List2,2);
	ListPushBack(&List2,4);
	ListPushBack(&List2,5);
	ListNode *result = MergeOrderedList(List1,List2);
	ListPrint(result);
}

上述代码过于重复冗长,我们对此进行优化后:

ListNode *MergeOrderedList(ListNode *List1,ListNode *List2)
{
	ListNode *cur1 = List1;
	ListNode *cur2 = List2;
	ListNode *result = NULL;
	ListNode *tail = NULL;
	ListNode *next;
	ListNode *node;

	//两个链表都不为空时
	while(cur1 != NULL && cur2 !=NULL)
	{
		
		//插入链表1的结点
		if(cur1->data <=cur2->data)
		{
			node = cur1;
		}
		else
		{
			node = cur2;
		}
			//结果链表不为空
			next = node->next;
			if(result !=NULL)
			{
				tail->next = node;	
			}
			//结果链表为空
			else
			{
				result = node;
			}
			node->next = NULL;
			tail = node;

			if(node == cur1)
			{
				cur1 = next;
			}
			else
			{
				cur2 = next;
			}
		}
	//有一个链表为空时
	if(cur1 ==NULL)
	{
		tail->next = cur2;
	}
	if(cur2 == NULL)
	{
		tail->next = cur1;
	}
	return result;
}
void ListPrint(ListNode *first)
{
	for(ListNode *cur = first;cur!=NULL;cur = cur->next)
	{
		printf("%d-> ",cur->data);
	}
	printf("NULL\n");
}

void TestMerge()
{
	ListNode *List1 = NULL;
	ListNode *List2 = NULL;

	ListPushBack(&List1,1);
	ListPushBack(&List1,1);
	ListPushBack(&List1,3);
	ListPushBack(&List1,4);
	ListPushBack(&List1,6);
	ListPushBack(&List1,7);

	ListPushBack(&List2,1);
	ListPushBack(&List2,2);
	ListPushBack(&List2,4);
	ListPushBack(&List2,5);
	ListNode *result = MergeOrderedList(List1,List2);
	ListPrint(result);
}

最后的结果为:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41420688/article/details/82980648