题目

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.

思路

这道题目是要复制一个副本,这里必须要保证两个链表不占用同一个空间,意思就是要新开辟一个空间,因此我们采用hashmap的思路,来存储对应node之间的关系。

代码
/**
 * 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) {
        if (head==NULL)
            return NULL;
        unordered_map<RandomListNode*,RandomListNode*> mp;
        RandomListNode* node = head;
        //loop1:copy and construct
        while(node)
        {
            mp[node] = new RandomListNode(node->label);
            node = node->next;
        }
        node = head;
        //loop2:assigh node
        while(node)
        {
            mp[node]->next = mp[node->next];
            mp[node]->random = mp[node->random];
            node = node->next;
        }
        return mp[head];
    }
};