剑指 Offer 35. 复杂链表的复制


请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

   示例 1:

    

      输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
      输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

   示例 2:

    

      输入:head = [[1,1],[2,1]]
      输出:[[1,1],[2,1]]
===========================================================================
思路:
做了几道剑指的题,感觉剑指的题理解起来是有点费劲,这个题目其实就是新建链表,复制之前链表的值,我才用了hash的方法,用hash保存了地址和下标的映射,上代码:
class Solution {
private:
    unordered_map<char *,int> map = {};
public:
    Node* copyRandomList(Node* head) {
        Node* h = head;
        vector nodes;
        Node *newhead = (Node*)malloc(sizeof(Node));
        if (!head)
            return head;
    
        *newhead = *head;
        nodes.push_back(newhead);
        int i = 0;
        map[(char*)head] = i;
        head = head->next;
        while (head) {
            Node *n = (Node*)malloc(sizeof(Node));
            *n = *head;
            newhead->next = n;
            i++;
            map[(char*)head] = i;
            newhead = n;
            nodes.push_back(newhead);
            head = head->next;
        }
        int j = 0;
        while (h) {
            if (h->random!= NULL) {
                nodes[j]->random = nodes[map.find((char*)h->random)->second];
            }
            h = h->next;
            j++;
        }
        return nodes[0];
    }
};
其实可以不用映射下标,直接映射地址,这样的话就不用vector的空间。
我看到官方的解题,第一个就是用hash映射,第二个是链表的拼接和拆分。。。太强了

先拼接再拆分,学到了