【LeetCode】Copy List with Random Pointer

来源:互联网 发布:刷q币软件 编辑:程序博客网 时间:2024/05/16 17:49

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

思路:总共分为三个函数来解决,可以参照《剑指offer》4.4的26题。

①先复制所有的节点,把复制的节点直接挂到原始节点后面,所以每两个节点值就是一样的;

②然后将复制的节点的random指针指点前驱节点的random指针指向的下一个节点;

③拆分链表成两个。

/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { *     int label; *     RandomListNode *next, *random; *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */class Solution {public:    void CloneList(RandomListNode *head){        RandomListNode *pNode=head;        while(pNode!=NULL){            RandomListNode* tmp=new RandomListNode(pNode->label);            //tmp->label=pNode->label;            tmp->next=pNode->next;            tmp->random=NULL;                        pNode->next=tmp;            pNode=tmp->next;        }     }        void CloneRandom(RandomListNode *head){        RandomListNode *pNodeold=head;        while(pNodeold!=NULL){            if(pNodeold->random!=NULL){                pNodeold->next->random=pNodeold->random->next;            }            pNodeold=pNodeold->next->next;        }    }        RandomListNode *DevideList(RandomListNode *head){        RandomListNode *pNodeold=head;        RandomListNode *headnew=NULL;        RandomListNode *pNodenew=NULL;        if(pNodeold!=NULL){            headnew=pNodenew=head->next;            pNodeold->next=pNodenew->next;            pNodeold=pNodeold->next;        }        while(pNodeold!=NULL){            pNodenew->next=pNodeold->next;            pNodenew=pNodenew->next;                        pNodeold->next=pNodenew->next;            pNodeold=pNodeold->next;        }        return headnew;    }        RandomListNode *copyRandomList(RandomListNode *head) {        if(head==NULL)return NULL;        CloneList(head);        CloneRandom(head);        return DevideList(head);    }};



0 0
原创粉丝点击