数据结构练习(37)复杂链表的复制

http://zhedahht.blog.163.com/blog/static/254111742010819104710337/

思路:

最后一种方法实在是巧妙,关于链表操作确实有很多精彩的地方,还需要不断的积累才行啊。

struct ComplexNode {
    int m_value;
    ComplexNode* m_pNext;
    ComplexNode* m_pSibling;
};

void CloneNodes(ComplexNode* pHead)
{
    ComplexNode* pNode = pHead;

    while (pNode != NULL)
    {
        ComplexNode* pClone = new ComplexNode;
        pClone->m_value = pNode->m_value;
        pClone->m_pNext = pNode->m_pNext;
        pClone->m_pSibling = NULL;

        pNode->m_pNext = pClone;
        pNode = pNode->m_pNext;
    }
}

void ConnectSiblingNodes(ComplexNode* pHead)
{
    ComplexNode* pNode = pHead;

    while (pNode != NULL)
    {
        ComplexNode* pClone = pNode->m_pNext;
        if (pClone && pNode->m_pSibling)
            pClone->m_pSibling = pNode->m_pSibling->m_pNext;
        pNode = pClone->m_pNext;
    }
}

ComplexNode* ReconnectNodes(ComplexNode* pHead)
{
    ComplexNode* pNode = pHead;
    ComplexNode* pCloneHead = NULL;
    ComplexNode* pCloneNode = NULL;

    if (pNode != NULL)
    {
        pCloneHead = pNode->m_pNext;
        pCloneNode = pCloneHead;
        pNode->m_pNext = pCloneHead->m_pNext;
        pNode = pNode->m_pNext;
    }
  
    while (pNode != NULL)
    {
        pCloneNode->m_pNext = pNode->m_pNext;
        pCloneNode = pCloneNode->m_pNext;

        pNode->m_pNext = pCloneNode->m_pNext;
        pNode = pNode->m_pNext;
    }

    return pCloneHead;
}

ComplexNode* Clone(ComplexNode* pHead)
{
    CloneNodes(pHead);
    ConnectSiblingNodes(pHead);
    return ReconnectNodes(pHead);
}

 

posted @ 2012-12-21 16:02  kedebug  阅读(476)  评论(0编辑  收藏  举报