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

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值