归并链表是将两个链表合成一个链表,
合并后的链表依旧有序(升序)。
当然,前提是两个链表归并之前已经是有序的。
好了,废话不多说。
要是想了解MyList类的结构,请参考链表常用函数
源代码:
MyList.h
void Merge(MyList& other); // 归并链表
MyList.cpp
void MyList::Merge(MyList& other)
{
if (NULL == other.m_pHead)
return;
if (NULL == m_pHead)
{
m_pHead = other.m_pHead;
other.m_pHead = NULL;
return;
}
ListNode* pNewHead = NULL;
ListNode* pNewCur = NULL;
ListNode* pMyCur = m_pHead;
ListNode* pOtherCur = other.m_pHead;
// 确定新链表的头结点
if (pMyCur->nData < pOtherCur->nData)
{
pNewCur = pMyCur;
pMyCur = pMyCur->pNext;
}
else
{
pNewCur = pOtherCur;
pOtherCur = pOtherCur->pNext;
}
pNewHead = pNewCur;
// 将两个链表中的节点链入新链表
while (pMyCur != NULL && pOtherCur != NULL)
{
if (pMyCur->nData < pOtherCur->nData)
{
pNewCur->pNext = pMyCur;
pNewCur = pMyCur;
pMyCur = pMyCur->pNext;
}
else
{
pNewCur->pNext = pOtherCur;
pNewCur = pOtherCur;
pOtherCur = pOtherCur->pNext;
}
}
// 链入剩余节点
if (pMyCur != NULL)
pNewCur->pNext = pMyCur;
else
pNewCur->pNext = pOtherCur;
// 修改头指针
other.m_pHead = NULL;
m_pHead = pNewHead;
}