1. 程式人生 > >排序單鏈表、 並兩個有序連結串列, 合併後依然有序

排序單鏈表、 並兩個有序連結串列, 合併後依然有序

建立連結串列節點結構

<span style="font-family:Microsoft YaHei;">typedef struct strNode
{
	struct strNode* pNext;
	DataType  data;
}Node;

typedef struct strNode*  PNode;</span>

連結串列的排序,在這裡就是對於每個節點所存數字的比較。

<span style="font-family:Microsoft YaHei;">void Bubble_Pnode(PNode pHead)
{
	PNode p1 = NULL;
	PNode p2 = NULL;
	assert(pHead);
	if (pHead->pNext == NULL)
	{
		return pHead;
	}
	p1 = pHead;
	while (p1 != NULL)
	{
		p2 = p1->pNext;
		while (p2 != NULL)   
		{
			if (p1->data > p2->data)   //從小到大   
			{
				DataType temp = p1->data;
				p1->data = p2->data;
				p2->data = temp;
			}
			p2 = p2->pNext;
		}
		p1 = p1->pNext;
	}
}</span>

其實這裡我採用了比較笨的辦法,就是先連結兩個連結串列,然後重新排序依次就好了。

<span style="font-family:Microsoft YaHei;">PNode merge_Node(PNode pHead1, PNode pHead2)//合併兩個有序連結串列
{
	PNode pH1 = pHead1;
	PNode pH2 = pHead2;
	PNode pphead = NULL;
	assert(pHead1&&pHead2);
	while (pH1->pNext != NULL)
	{
		pH1 = pH1->pNext;
	}
	pH1->pNext = pH2;
	pphead = pHead1;
	Bubble_Pnode(pphead);
	return pphead;
}</span>

//修改:2016-10-3

node* Merge(node* phead1, node* phead2)
{
	if (NULL == phead1)
		return phead2;
	else if (NULL == phead2)
		return phead1;
	node* pMergeHead = NULL;
	if (phead1->data < phead2->data)
	{
		pMergeHead = phead1;
		pMergeHead->next = Merge(phead1->next, phead2);
	}
	else
	{
		pMergeHead = phead2;
		pMergeHead->next = Merge(phead1, phead2->next);
	}
	return  pMergeHead;
}
當然,也可以使用迴圈來做 , 留給讀者了。。。