您的位置:首页 > 其它

复杂链表的复制

2016-05-20 15:36 246 查看
//请实现函数ComplexListNode* Clone(ComplexListNode* pHead),复制一个复杂链表。
//在复杂链表中,每个结点除了有一个m_pNext指针指向下一个结点外,还有一个m_pSlibling
//指向链表中的任意结点或者NULL。
#include <map>

using namespace std;

struct ComplexListNode
{
int m_nValue;
ComplexListNode* m_pNext;
ComplexListNode* m_pSibling;
};

ComplexListNode* singleListCopy(ComplexListNode* pHead)
{
if (pHead == NULL)
return NULL;

ComplexListNode* newp = new ComplexListNode();

newp->m_nValue = pHead->m_nValue;
newp->m_pSibling = NULL;
newp->m_pNext = singleListCopy(pHead->m_pNext);
}

ComplexListNode* clone0(ComplexListNode* pHead)
{
if (pHead == NULL)
return NULL;
map<ComplexListNode*, ComplexListNode*> nodeMap;
ComplexListNode* pNewHead = singleListCopy(pHead);

ComplexListNode* oldp = pHead;
ComplexListNode* newp = pNewHead;
while (oldp != NULL)
{
nodeMap[oldp] = pNewHead;
oldp = oldp->m_pNext;
newp = newp->m_pNext;
}

oldp = pHead;
newp = pNewHead;

while (oldp != NULL)
{
newp->m_pSibling = nodeMap[oldp->m_pSibling];
oldp = oldp->m_pNext;
newp = newp->m_pNext;
}
return pNewHead;
}

//不用map,复杂度也是O(n),只是稍微麻烦一点。
void cloneNodes(ComplexListNode* pHead)
{
ComplexListNode* pOld = pHead;
while (pOld != NULL)
{
ComplexListNode *pNew = new ComplexListNode();
pNew->m_nValue = pOld->m_nValue;

pNew->m_pNext = pOld->m_pNext;
pOld->m_pNext = pNew;
pOld = pNew->m_pNext;

pNew->m_pSibling = NULL;
}
}

void connectSiblingNodes(ComplexListNode* pHead)
{
ComplexListNode* pOld = pHead;

while (pOld != NULL)
{
ComplexListNode* pNew = pHead->m_pNext;
if (pOld->m_pSibling != NULL)
pNew->m_pSibling = pOld->m_pSibling->m_pNext;
pOld = pNew->m_pNext;
}
}

ComplexListNode* reconnectNodes(ComplexListNode* pHead)
{
if (pHead == NULL)
return NULL;

ComplexListNode* pOld = pHead;
ComplexListNode* pNewHead = pHead->m_pNext;
ComplexListNode* pNew = pNewHead;

while (pNew->m_pNext != NULL)
{
pOld->m_pNext = pNew->m_pNext;
pOld = pNew->m_pNext;
pNew->m_pNext = pOld->m_pNext;
pNew = pOld->m_pNext;
}
pOld->m_pNext = NULL;
return pNewHead;
}

ComplexListNode* clone1(ComplexListNode* pHead)
{
cloneNodes(pHead);
connectSiblingNodes(pHead);
return reconnectNodes(pHead);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: