剑指 Offer 35. 复杂链表的复制(含random指针)

普通链表复制

class Solution {
public:
    Node* copyRandomList(Node* head) {
        Node* cur = head;
        Node* dum = new Node(0), *pre = dum;
        while(cur != nullptr) {
            Node* node = new Node(cur->val); // 复制节点 cur
            pre->next = node;                // 新链表的 前驱节点 -> 当前节点
            // pre->random = "???";          // 新链表的 「 前驱节点 -> 当前节点 」 无法确定
            cur = cur->next;                 // 遍历下一节点
            pre = node;                      // 保存当前新节点
        }
        return dum->next;
    }
};
/*
// 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 == nullptr)
            return nullptr;
        unordered_map<Node*, Node*> res;
        Node* cur = head;
        while(cur!=nullptr)
        {
            res[cur] = new Node(cur->val);
            cur = cur->next;
        }
        cur = head;
        while(cur!=nullptr)
        {
            res[cur]->next = res[cur->next];
            res[cur]->random = res[cur->random];
            cur = cur->next;
        }
        return res[head];
    }
};

链表拼接+拆分

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head == nullptr)
            return nullptr;
        Node* cur = head;
        //在原链表基础上拼接新链表 如 7-7-2-2-3-3-1-1
        while(cur!=nullptr)
        {
            Node* tmp = new Node(cur->val);
            tmp->next = cur->next;
            cur->next = tmp;//这两句将tmp插入到原链表中即7-7-2-3-1
            cur = tmp->next;//这两句将cur移向2即cur->next->next
        }
        //求新链表的random
        cur = head;
        while(cur!=nullptr)
        {
            if(cur->random != nullptr)
                cur->next->random = cur->random->next; //左式中cur->next即复制好的新节点,右式中cur->random->next其值与cur->random相同,即新复制好的链表
            cur = cur->next->next;
        }
        //拆分链表
        cur = head->next;
        Node* pre = head, *res = head->next;
        while(cur->next != nullptr)
        {
            pre->next = pre->next->next;
            cur->next = cur->next->next;
            pre = pre->next;
            cur = cur->next;
        }
        pre->next = nullptr;
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值