(c++)(两种方案)剑指offer:复杂链表的复制。

题目
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
法1:哈希表关联容器。

复杂链表的复制涉及到深拷贝,因为除了next指针还有random指针。random指针寻找定位,一般都会考虑到先复制完所有next,然后每个指针的random从头开始遍历。这样时间复杂度太高。O(N^2)
考虑到random指针把两个节点的关系联系了起来,所以思路可以开展到哈希表关联容器上,辅助实现深拷贝。用空间换时间

unordered_map<node*,node*>mp,
实现的是复制与深拷贝后一一对应的节点。
刚开始的深拷贝,将原先的节点深拷贝后的儿子放入map与其父亲一一对应

mp[t]=new Node(t->val);

next与random指针的复制对应关系!想清楚用unordered_map的实现!

mp[t]->next=mp[t->next];
mp[t]->random=mp[t->random];

代码:

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    Node* copyRandomList(Node* head) 
    {
        if(!head) return head;
        unordered_map<Node*,Node*>mp;
        Node*cur=head;
        while(cur)
        {
            mp[cur]=new Node(cur->val);
            cur=cur->next;
        }
        cur=head;
        while(cur)
        {
            mp[cur]->next=mp[cur->next];
            if(cur->random)
            mp[cur]->random=mp[cur->random];
            cur=cur->next;
        }
        return mp[head];
    }
};

法2.原地复制
比如1->1->3 复制为 1->1->1->1->3->3;
random也要复制
完成后,返回复制的部分。

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    void copyforNext(Node*&head)
    {
        if(!head) return ;
        while(head)
        {
            Node* temp=new Node(head->val);
            temp->next=head->next;
            head->next=temp;
            head=temp->next;
        }
    }
    void copyforRandom(Node*&head)
    {
        if(!head) return ;
        while(head)
        {
            Node*temp=head->next;
            if(head->random)
            {
                temp->random=head->random->next;
            }
            head=temp->next;
        }
    }
    Node* getCopyRES(Node*&head)
    {
        if(!head) return head;
        Node*copyRes=head->next;
        Node*tempRes=copyRes;
        while(head)
        {
           head->next=head->next->next;
           head=head->next->next;  
           if(tempRes->next)   
               {tempRes->next=tempRes->next->next;
               tempRes=tempRes->next->next;}
               else tempRes->next=NULL;
        }
        return copyRes;
    }
    Node* copyRandomList(Node* &head) 
    {

        if(!head) return head;
        copyforNext(head);
        copyforRandom(head);
        return getCopyRES(head);   
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值