您的位置:首页 > 其它

合并两个有序单链表

2017-07-13 15:05 381 查看
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_v
4000
alue)
{
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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: