JZ35 && LQ138 复杂链表的复制 哈希表法+拼接拆分

哈希

  • 两步走
    • 第一次赋值val和next,构造哈希表 key:旧链表结点,value对应位置的新链表的结点
    • 第二次重新从头走一遍,通过哈希表记住random:
      • 新链表和旧链表同时移动,旧链表当前指针作为key,value为当时和对应的新链表
      • 与此同时 dic[旧链表当前指针->random]即为对应的新链表当前指针->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) {
        Node* start = new Node(0);
        Node* s2 = start;
        Node* cur = head;
        unordered_map<Node*, Node*> m;
        while(cur!=nullptr){
            start->next = new Node(cur->val);
            start=start->next;
            m[cur] = start;
            cur=cur->next;
        }
        start = s2->next;
        cur = head;
        while(cur!=nullptr){
            start->random = m[cur->random];
            start=start->next;
            cur=cur->next;
        }
        //cout<<s2->next->val<<" "<<s2->next->random->val;
        return s2->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;
        Node* cur = head;
        // 1. 复制各节点,并构建拼接链表
        while(cur != nullptr) {
            Node* tmp = new Node(cur->val);
            tmp->next = cur->next;
            cur->next = tmp;
            cur = tmp->next;
        }
        // 2. 构建各新节点的 random 指向
        cur = head;
        while(cur != nullptr) {
            if(cur->random != nullptr)
                cur->next->random = cur->random->next; // cur->random->next 即根据旧random节点找到对应新random节点,因为两者是连在一起的
            cur = cur->next->next;
        }
        // 3. 拆分两链表
        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、付费专栏及课程。

余额充值