题目描述:

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。

注意:输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空。

/* struct RandomListNode { int label; struct RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) { } }; */
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        CloneNodes(pHead);
        ConnectRandom(pHead);
        return ReConnectNodes(pHead);
    }
private:
    void CloneNodes(RandomListNode* pHead){
        RandomListNode *pNode = pHead;
        while(pNode != NULL){
            RandomListNode *pCloned = new RandomListNode(0);
            pCloned->label = pNode->label;
            pCloned->next = pNode->next;
            pCloned->random = NULL;

            pNode->next = pCloned;

            pNode = pCloned->next;
        }
    }

    void ConnectRandom(RandomListNode* pHead){
        RandomListNode *pNode = pHead;
        while(pNode){
            RandomListNode *pCloned = pNode->next;
            if(pNode->random != NULL)
                pCloned->random = pNode->random->next;
            pNode = pCloned->next;
        }
    }

    RandomListNode* ReConnectNodes(RandomListNode* pHead){
        RandomListNode *pNode = pHead;
        RandomListNode *pClonedNode = NULL;
        RandomListNode *pClonedHead = NULL;
        if(pNode != NULL){
            pClonedNode = pClonedHead = pNode->next;
            pNode->next = pClonedNode->next;
            pNode = pNode->next;
        }
        while(pNode){
            pClonedNode->next = pNode->next;
            pClonedNode = pClonedNode->next;
            pNode->next = pClonedNode->next;
            pNode = pNode->next;
        }
        return pClonedHead;
    }
};

如有建议或其他问题,可随时给我们留言。或者到以下链接:

https://github.com/gaobaoru/code_day

Star/Fork/Push 您的代码,开源仓库需要您的贡献。

请查看Coding 题目网址和收藏Accepted代码仓库,进行coding!!!