关闭

复杂链表的复制

415人阅读 评论(0) 收藏 举报
分类:

解法一:


解法二:



void CloneNodes(ComplexListNode* pHead)
{
ComplexListNode* pNode = pHead;
while (pNode != NULL)
{
ComplexListNode* pCLoned = new ComplexListNode();
pCloned->m_nValue = pNode->m_nValue;
pCloned->m_pNext = pNode->m_pNext;
pNode->m_pNext = pCloned;
pNode = pCloned->m_pNext;
}
}


void ConnectSiblingNodes(ComplexListNode* pHead)
{
ComplexListNode* pNode = pHead;
while (pNode != NULL)
{
ComplexListNode*pCloned = pNode->m_pNext;
if (pNode->m_pSibling != NULL)
{
pCloned->m_pSibling = pNode->m_pSibling->m_pNext;


}
pNode = pCloned->m_pNext;
}
}


ComplexListNode* ReconnectNodes(ComplexListNode* pHead)
{
ComplexListNode* pNode = pHead;
ComplexListNode* pClonedHead = NULL;
ComplexListNode* pClonedNode = NULL;
if (pNode != NULL)
{
pClonedHead = pClonedNode = pNode->m_pNext;
pNode->m_pNext = pClonedNode->m_pNext;
}
while (pNode != NULL)
{
pClonedNode->m_pNext = pNode->m_pNext;
pClonedNode = pClonedNode->m_pNext;
pNode->m_pNext = pClonedNode->m_pNext;
pNode = pNode->m_pNext;
}
return pClonedHead;
}

把上面三步合起来,就是复制链表的完整过程:

ComplexListNode* Clone(ComplexListNode* pHead)

{

       CloneNodes(pHead);

       ConnectSiblingNodes(pHead);

       return ReconnectNodes(pHead);

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:156838次
    • 积分:6151
    • 等级:
    • 排名:第4031名
    • 原创:479篇
    • 转载:2篇
    • 译文:1篇
    • 评论:3条
    最新评论