• 面试题26:复杂链表的复制


    题目描述

    有一个复杂链表,其结点除了有一个m_pNext指针指向下一个结点外,还有一个m_pSibling指向链表中的任一结点或者NULL请完成函数ComplexListNode* Clone(ComplexListNode* pHead),以复制一个复杂链表。结点的定义如下:

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

    题目分析

    剑指Offer(纪念版)P147

    代码实现

    ComplexListNode* Clone(ComplexListNode* pHead)
    {
        CloneNodes(pHead);
        ConnectSiblingNodes(pHead);
        return ReconnectNodes(pHead);
    }
    
    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;
            pCloned->m_pSibling = NULL;
     
            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;
            pNode = pNode->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;
    }
    

      

  • 相关阅读:
    关键词提取算法TextRank
    我的博文目录整理
    Windows Azure一些小技巧集合
    js数组和树互转
    this.props.form.validateFields回调不执行问题
    d3的4.x与3.x版本的区别
    d3提示框,虚线,选择区域
    d3布局
    d3文件导入和导出
    d3交互
  • 原文地址:https://www.cnblogs.com/xwz0528/p/4832406.html
Copyright © 2020-2023  润新知