leetcode138.随机链表的复制

leetcode138.随机链表的复制

随机链表的复制

首先,我们需要一个类型为的哈希表,命名为hashhash.first存的是旧链表的节点,hash.second存的是新链表的结点,一次遍历旧链表后,我们的就把新节点“挂”在与旧链表一一对应的旧节点下

while(cur)
{
    hash.insert({cur,new Node(cur->val)});
    cur = cur->next;
}

此时新节点的nextrandom还没有赋值,就需要我们第二次遍历链表,通过哈希表找到新节点指向的的nextrandom

while(cur)
{
    hash[cur]->next = hash[cur->next];
    hash[cur]->random =hash[cur->random];
    cur = cur->next;
}

最后返回hash[head]

Node* copyRandomList(Node* head) {
    unordered_map<Node*,Node*> hash;
    Node* cur =  head;
    while(cur)
    {
        hash.insert({cur,new Node(cur->val)});
        cur = cur->next;
    }
    cur = head;
    while(cur)
    {
        hash[cur]->next = hash[cur->next];
        hash[cur]->random =hash[cur->random];
        cur = cur->next;
    }
    return hash[head];
}

你可能感兴趣的:(算法,链表,哈希算法,数据结构)