1. 程式人生 > >C++ 合併兩個有序單向連結串列

C++ 合併兩個有序單向連結串列

struct Node
{
	Node* pNext;
	int val;
	Node(int v)
	{
		val = v;
		pNext = nullptr;
	}
};
Node* MergeNodeList(Node* p1,Node*p2)
{
	Node *pRoot,*pCur;

	if (p1->val < p2->val)
	{
		pRoot = p1;
		p1 = p1->pNext;
	}
	else
	{
		pRoot = p2;
		p2 = p2->pNext;
	}
	pCur = pRoot;
	while(p1 && p2)
	{
		if (p1->val < p2->val)
		{
			pCur->pNext = p1;
			p1 = p1->pNext;
		}
		else{
			pCur->pNext = p2;
			p2 = p2->pNext;
		}
		pCur = pCur->pNext;
	}
	if (p1)
		pCur->pNext = p1;
	if (p2)
		pCur->pNext = p2;
	return pRoot;
}