题目

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

分析

实现一个链表的深拷贝,返回拷贝后的新链表。

若是普通链表,逐个拷贝原始链表节点并连接即可,只需O(n)的时间复杂度;但是此题特殊的是,每个节点都有一个random域可以指向该链表中的任何一个节点,所以直接复制无法处理random域,因为其指向的节点很有可能还没有创建出来。

有两种方法处理:

方法一:暴力解决,首先不处理random域,将原始链表复制一份,然后遍历每个原始链表节点,查找其random域,将新链表的对应节点链接,该方法需要O(n^2)的时间复杂度,给出的结果是TLE。

方法二:充分利用原始链表的信息,不用保存原始链表的映射关系,构建新节点时,指针做如下变化,即把新节点插入到相应的旧节点后面(参考):



同理分两步

1、构建新节点random指针:

new1->random = old1->random->next, new2-random = NULL,
new3-random = NULL, new4->random = old4->random->next

2、恢复原始链表以及构建新链表:

old1->next = old1->next->next,  new1->next = new1->next->next

该算法时间复杂度O(N),空间复杂度O(1)

AC代码

class Solution {
public:
//方法一:直接复制,再修改random指针
RandomListNode *copyRandomList1(RandomListNode *head) {
if (!head)
return NULL; RandomListNode *ret = new RandomListNode(head->label), *q = ret;
RandomListNode *p = head->next;
while (p)
{
RandomListNode *tmp = new RandomListNode(p->label);
q->next = tmp;
q = q->next; p = p->next;
}//while
q->next = NULL; //处理原始链表的random指针
p = head, q = ret;
RandomListNode *idx1 = head, *idx2 = ret;
while (p)
{
if (p->random == NULL)
q->random = NULL;
else{
idx1 = head;
idx2 = ret;
while (p->random->label != idx1->label)
{
idx1 = idx1->next;
idx2 = idx2->next;
}//while
q->random = idx2;
}//else
p = p->next;
q = q->next;
}//while
return ret;
} //方法二:充分利用原始链表信息,在每个节点后复制添加
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head)
return NULL; //首先,复制原始的节点,连接自身后面
RandomListNode *p = head;
while (p)
{
RandomListNode *tmp = new RandomListNode(p->label);
//保存后续节点
RandomListNode *r = p->next; tmp->next = r;
p->next = tmp; p = r;
}//while //然后,将添加的节点random 链接到原始节点random的下一个位置
p = head;
while (p)
{
RandomListNode *q = p->next;
if (p->random == NULL)
q->random = NULL;
else{
q->random = p->random->next;
}//else
//处理下一个原始节点
p = q->next;
}//while //最后,恢复原始链表,得到新链表
RandomListNode *ret = head->next; p = head;
RandomListNode *q = head->next;
while (q->next)
{
p->next = q->next;
p = q;
if (q->next)
q = q->next;
}
p->next = NULL;
q->next = NULL;
return ret;
} };

GitHub测试程序源码

LeetCode(138) Copy List with Random Pointer的更多相关文章

  1. 133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表

    133. Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of it ...

  2. 【LeetCode练习题】Copy List with Random Pointer

    Copy List with Random Pointer A linked list is given such that each node contains an additional rand ...

  3. [Leetcode Week17]Copy List with Random Pointer

    Copy List with Random Pointer 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/copy-list-with-random- ...

  4. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  5. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  6. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  7. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  8. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  9. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

随机推荐

  1. 分布式Job系统Hangfire

    开源分布式Job系统,调度与业务分离-如何创建一个计划HttpJob任务   项目介绍: Hangfire:是一个开源的job调度系统,支持分布式JOB!! Hangfire.HttpJob 是我针对 ...

  2. .NET Core中Circuit Breaker

    谈谈Circuit Breaker在.NET Core中的简单应用 前言 由于微服务的盛行,不少公司都将原来细粒度比较大的服务拆分成多个小的服务,让每个小服务做好自己的事即可. 经过拆分之后,就避免不 ...

  3. bzoj 2301: [HAOI2011]Problem b mobius反演 RE

    http://www.lydsy.com/JudgeOnline/problem.php?id=2301 设f(i)为在区间[1, n]和区间[1, m]中,gcd(x, y) = i的个数. 设F( ...

  4. 关于Linux系统启动时出现UVD not responding, Trying to reset the vcpu问题的解决

    本人的老古董笔记本!不知道什么时候显卡烧坏了 每次启动Linux的时候就会出现错误,信息如下: UVD not responding, trying to reset the VCPU! 讲道理,显卡 ...

  5. Android仿360悬浮小球自定义view实现

    转载请标明出处:http://www.jianshu.com/u/a5ad093cffe8 效果图如下: 图片.png   图片.png 实现当前这种类似的效果 (360小球 悬浮桌面差不错类似).第 ...

  6. Git中文件属性的变化,被认为是文件有改动

    问题描述: 1.  从公司的git服务器上, 下载最新的代码(zip格式), 解压缩出来, 2.  过一段时间, 去执行git pull代码, 出现如下情况: $ git pull Updating ...

  7. 解决ajax 遇到session失效后自动跳转的问题

    在项目中,经常会遇到session失效后,点击任何链接无反应的情况!这样给客户的体验就不是很好,以为是系统出了故障!所以在项目中我们会处理session失效后的跳转问题(一般给用户提示,并跳转后登录页 ...

  8. [论文理解] Connectionist Text Proposal Network

    Connectionist Text Proposal Network 简介 CTPN是通过VGG16后在特征图上采用3*3窗口进行滑窗,采用与RPN类似的anchor机制,固定width而只预测an ...

  9. mybatis(一):思维导图

  10. python 基础之格式化输出

    字符占位符%s #_cvvh:"chenxi" #date: 2019/6/24 print ('chhjg') # 格式化输出 name = input("Name:& ...