leetcode-Copy List with Random Pointer

来源:互联网 发布:时序数据挖掘 编辑:程序博客网 时间:2024/06/03 17:50

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.

/** * 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:    RandomListNode *copyRandomList(RandomListNode *head) {        RandomListNode *temp = head;        vector<int> a;        vector<RandomListNode*> b;        int i = 0;        while(temp)        {            a.push_back(temp->label);            temp->label = i;            temp = temp->next;            i++;        }        temp = head;                RandomListNode *nhead = NULL;        RandomListNode *temp1 = NULL;        i = 0;        int n = a.size();        while(i < n)        {            if(nhead == NULL)            {                nhead = new RandomListNode(i);                temp1 = nhead;                b.push_back(temp1);            }            else            {                RandomListNode *node = new RandomListNode(i);                temp1->next = node;                temp1 = node;                b.push_back(temp1);            }            i++;        }                temp = head;        temp1 = nhead;        while(temp)        {            if(temp->random == NULL)            {                temp1->random = NULL;            }            else            {                int j = temp->random->label;                temp1->random = b[j];            }            temp = temp->next;            temp1 = temp1->next;        }                temp = head;        temp1 = nhead;        i = 0;        while(i < n)        {            temp->label = a[i];            temp1->label = a[i];            temp = temp->next;            temp1 = temp1->next;            i++;        }                return nhead;    }};


0 0
原创粉丝点击