138. 复制带随机指针的链表

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的 深拷贝。 

我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。
 

示例 1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:

输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:

输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例 4:

输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。
 

提示:

-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。

/*
// 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 == NULL)
            return head;
        /*map<Node*, Node*> ump;
        Node* cur = head;
       // 将原始节点作为key,新节点作为value存入map 
        while(cur != NULL) {
            Node* cc = new Node(cur->val);
            ump[cur] = cc;
            cur = cur->next;
        }
        cur = head;
        while(cur != NULL) {
            ump[cur]->random = ump[cur->random];
            ump[cur]->next = ump[cur->next];
            cur = cur->next;
        }
        return ump[head];*/
        Node *cur = head;
        //1.在原来节点后加相同节点
        while(cur != NULL) {
            Node *temp = new Node(cur->val);
            temp->next = cur->next;
            cur->next = temp;
            cur = cur->next->next;
        }
        cur = head;
        //2.复制random节点
        while(cur != NULL) {
            if(cur->random != NULL) {
                cur->next->random = cur->random->next;
            }
            cur = cur->next->next;
        }
        cur = head;
        Node *Ret = head->next;
        Node *Rettemp = Ret;
        //3.拆分
        while(cur != NULL) {
            cur->next = cur->next->next;
            if(Rettemp->next != NULL) {
                Rettemp->next = Rettemp->next->next;
            }
            cur = cur->next;
            Rettemp = Rettemp->next;
        }
        return Ret;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值