AcWing 48. 复杂链表的复刻(C++)- 链表

题目链接:https://www.acwing.com/problem/content/description/89/
题目如下:
在这里插入图片描述

/**
 * Definition for singly-linked list with a random pointer.
 * struct ListNode {
 *     int val;
 *     ListNode *next, *random;
 *     ListNode(int x) : val(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode *copyRandomList(ListNode *head) {
    
    
        //思路:在哈希表中,存储[原链表节点,目标链表节点],遍历原链表
        //判断每个节点和random节点是否在umap中,如果不存在则创建
        unordered_map<ListNode*,ListNode*> umap;
        umap[nullptr]=nullptr;
        auto dummy=new ListNode(-1);
        auto tail=dummy;
        
        while(head!=NULL){
    
    
            if(umap.count(head)==0) umap[head]=new ListNode(head->val);
            if(umap.count(head->random)==0) umap[head->random]=new ListNode(head->random->val);
            
            tail->next=umap[head];
            tail->next->random=umap[head->random];
            
            tail=tail->next;
            head=head->next;
        }
        
        return dummy->next;
    }
};

おすすめ

転載: blog.csdn.net/qq_40467670/article/details/121344581