typedef struct Node
{
Node(const int& value)
: m_value(value)
, m_pNext(NULL)
{}
int m_value;
Node* m_pNext;
}Node, *pNode ;
class List
{
public:
List()
: _pHead(NULL)
, _pTail(NULL)
{}
void PushBack(const int& value)
{
if (_pHead == NULL)
{
_pHead = _pTail = _BuyNode(value);
}
else
{
Node* temp = _BuyNode(value);
_pTail->m_pNext = temp;
_pTail = temp;
}
}
pNode* CombineList(List pHead1, List pHead2)
{
if (pHead1._pHead == NULL || pHead2._pHead == NULL)
return NULL;
if (pHead1._pHead == NULL)
return &pHead2._pHead;
if (pHead2._pHead == NULL)
return &pHead1._pHead;
pNode pNewHead = NULL;
pNode pHead1Next = pHead1._pHead->m_pNext;
pNode pHead2Next = pHead2._pHead->m_pNext;
if (pHead1._pHead->m_value < pHead2._pHead->m_value)
{
pNewHead = pHead1._pHead;
pHead1._pHead = pHead1Next;
if (pHead1Next)
pHead1Next = pHead1Next->m_pNext;
pNewHead->m_pNext = NULL;
}
else
{
pNewHead = pHead2._pHead;
pHead2._pHead = pHead2Next;
if (pHead2Next)
pHead2Next = pHead2Next->m_pNext;
pNewHead->m_pNext = NULL;
}
pNode pNew = pNewHead;
while (pHead1._pHead&&pHead2._pHead)
{
if (pHead1._pHead->m_value < pHead2._pHead->m_value)
{
pNew->m_pNext = pHead1._pHead;
pHead1._pHead = pHead1Next;
if (pHead1Next)
pHead1Next = pHead1Next->m_pNext;
}
else
{
pNew->m_pNext = pHead2._pHead;
pHead2._pHead = pHead2Next;
if (pHead2Next)
pHead2Next = pHead2Next->m_pNext;
}
pNew = pNew->m_pNext;
}
if (pHead1._pHead)
pNew->m_pNext = pHead1._pHead;
if (pHead2._pHead)
pNew->m_pNext = pHead2._pHead;
return &pNewHead;
}
private:
pNode _BuyNode(const int& value)
{
return new Node(value);
}
private:
pNode _pHead;
pNode _pTail;
};
合并两个有序单链表
最新推荐文章于 2022-09-06 16:20:45 发布