复杂链表复制

来源:互联网 发布:linux 软阵列 编辑:程序博客网 时间:2024/05/16 19:24

这里写图片描述

#include <iostream>using namespace std;//复杂链表的复制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;        //将链表每个结点都复制相同一个在其后连接:如1->2->3->NULL变为1->1->2->2->3->3->NULL        RandomListNode* cur=pHead;        while(cur)        {            RandomListNode* NewNode=new RandomListNode(cur->label);            NewNode->next=cur->next;            cur->next=NewNode;            cur=cur->next->next;        }        //使复制的相同结点的随机指针指向前一个原结点随机指针下一个        cur=pHead;        while(cur)        {            RandomListNode* Next=cur->next;            if(cur->random)                Next->random=cur->random->next;            else                Next->random=NULL;            cur=cur->next->next;        }        //分解拆分链表成为两个        cur=pHead;        RandomListNode* head2=cur->next;        while(cur)        {            RandomListNode* Next=cur->next;            cur->next=Next->next;            if(cur->next)                Next->next=cur->next->next;            else                Next->next=NULL;            cur=cur->next;        }        return head2;    }};