您的位置:首页 > 其它

【刷题之路】复杂链表的复制

2016-07-18 14:55 246 查看
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head

三步走:

第一步,复制链表节点A->B->C 变为  A->A'->B->B'->C->C'  ,目的为了第二步

第二步,重建random指针位置,此时,复制后的指针指向的位置应该就是原节点random指针指向节点的next,这样就重建了复杂链表

第三步,将复制出的节点分离并组合成为一个新的链表,这就是我们复制出的链表

代码如下:

/*

struct RandomListNode {

    int label;

    struct RandomListNode *next, *random;

    RandomListNode(int x) :

            label(x), next(NULL), random(NULL) {

    }

};

*/

class Solution {

public:

    RandomListNode* Clone(RandomListNode* pHead)

    {

        if(pHead==NULL) return NULL; 

        RandomListNode* copyhead;

        RandomListNode* rebuild;

        RandomListNode* res;

        copyhead=Copy(pHead);

        rebuild=Rbuild(copyhead);

        res=Divide(rebuild);

        return res;

    }

    RandomListNode* Copy(RandomListNode* pHead){

        RandomListNode* temp=pHead;

        RandomListNode* next;

        while(temp){

        RandomListNode *node = new RandomListNode(temp->label);

            next=temp->next;

            temp->next=node;

            node->next=next;

            temp=next;

        }

        return pHead;

    }

    RandomListNode* Rbuild(RandomListNode* pHead){

        RandomListNode* temp=pHead;

        while(temp){

            if(temp->random) temp->next->random=temp->random->next;

            temp=temp->next->next;

        }

        return pHead;

    }

    RandomListNode* Divide(RandomListNode* pHead){

        RandomListNode* temp=pHead->next->next;

        RandomListNode* newhead=pHead->next;

        RandomListNode* newtemp=newhead;

        while(temp){

            newtemp->next=temp->next;

            newtemp=newtemp->next;

            temp=temp->next->next;

        }

        return newhead;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  刷题 链表