首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 138. 复制带随机指针的链表(哈希 / 深拷贝)

LeetCode 138. 复制带随机指针的链表(哈希 / 深拷贝)

作者头像
Michael阿明
发布2020-07-13 15:19:34
2700
发布2020-07-13 15:19:34
举报

1. 题目

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

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

在这里插入图片描述
在这里插入图片描述

《剑指Offer》同题:面试题35. 复杂链表的复制

2. 解题

  • 哈希表存储映射《原节点,新节点》
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head == NULL)
            return NULL;
        unordered_map<Node*, Node*> m;//原节点-新节点 哈希表
        Node *cur = head, *newNode;
        while(cur != NULL)//先创建新节点,赋值
        {
            newNode = new Node(cur->val);
            m[cur] = newNode;
            cur = cur->next;
        }
        cur = head;
        while(cur != NULL)//再次遍历,查表,把新节点指针付进去
        {
            m[cur]->next = m[cur->next];
            m[cur]->random = m[cur->random];
            cur = cur->next;
        }
        return m[head];
    }
};
在这里插入图片描述
在这里插入图片描述
  • 原地算法,先复制一遍链表 a ->a.-> b-> b.-> ...
  • 接好新链表random
  • 拆开两条链表
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(!head)
            return NULL;
        Node* cur = head, *newNode, *H;
        while(cur)//复制一遍原链表 a a` b b`... 
        {
        	newNode = new Node(cur->val);
        	newNode->next = cur->next;
        	cur->next = newNode;
        	cur = newNode->next;
        }
        cur = head;
        newNode = cur->next;
        while(cur)//把新链表的random接好
        {
            if(cur->random)
        	    newNode->random = cur->random->next;
        	cur = cur->next->next;
            if(cur)
        	    newNode = cur->next;
        }
        cur = head;
        H = newNode = cur->next;
        while(newNode->next)//两条链表拆开
        {
            cur->next = newNode->next;
        	newNode->next = newNode->next->next;
            cur = cur->next;
        	newNode = newNode->next;
        }
        cur->next = NULL;
        return H;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档