复杂链表的复制

解法一:


解法二:



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);

}


阅读更多
个人分类: 剑指offer
上一篇二叉树中和为某一值的路径
下一篇二叉搜索树与双向链表
博主设置当前文章不允许评论。

没有更多推荐了,返回首页

关闭
关闭