1. 程式人生 > >合併兩個有序連結串列,合併之後仍有序

合併兩個有序連結串列,合併之後仍有序

合併兩個有序連結串列,合併之後仍有序。

標頭檔案引用連結串列的一些基本操作
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);
}

最後的結果為:
在這裡插入圖片描述