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.

这道题的难点在于如何处理随机指针,由于每一个节点都有一个随机指针,这个指针可以为空,也可以指向链表的任意一个节点,如果在生成一个新节点给其随机指针赋值时,都去遍历原链表的话,OJ上肯定会超时。建立一个原节点和新节点的HashMap,给随机指针赋值时查找HashMap,这样可缩短查找时间。

解法1: HashMap

解法2:

Java:

public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return null;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode newHead = new RandomListNode(head.label); RandomListNode p = head;
RandomListNode q = newHead;
map.put(head, newHead); p = p.next;
while (p != null) {
RandomListNode temp = new RandomListNode(p.label);
map.put(p, temp);
q.next = temp;
q = temp;
p = p.next;
} p = head;
q = newHead;
while (p != null) {
if (p.random != null)
q.random = map.get(p.random);
else
q.random = null; p = p.next;
q = q.next;
} return newHead;
}

Java:

public RandomListNode copyRandomList(RandomListNode head) {

	if (head == null)
return null; RandomListNode p = head; // copy every node and insert to list
while (p != null) {
RandomListNode copy = new RandomListNode(p.label);
copy.next = p.next;
p.next = copy;
p = copy.next;
} // copy random pointer for each new node
p = head;
while (p != null) {
if (p.random != null)
p.next.random = p.random.next;
p = p.next.next;
} // break list to two
p = head;
RandomListNode newHead = head.next;
while (p != null) {
RandomListNode temp = p.next;
p.next = temp.next;
if (temp.next != null)
temp.next = temp.next.next;
p = p.next;
} return newHead;
}  

Python:   Time: O(n)  Space: O(n)

# Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None class Solution2:
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
dummy = RandomListNode(0)
current, prev, copies = head, dummy, {} while current:
copied = RandomListNode(current.label)
copies[current] = copied
prev.next = copied
prev, current = prev.next, current.next current = head
while current:
if current.random:
copies[current].random = copies[current.random]
current = current.next return dummy.next if __name__ == "__main__":
head = RandomListNode(1)
head.next = RandomListNode(2)
head.random = head.next
result = Solution().copyRandomList(head)
print(result.label)
print(result.next.label)
print(result.random.label)

Python: Time: O(n)  Space: O(1)

class Solution:
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
# copy and combine copied list with original list
current = head
while current:
copied = RandomListNode(current.label)
copied.next = current.next
current.next = copied
current = copied.next # update random node in copied list
current = head
while current:
if current.random:
current.next.random = current.random.next
current = current.next.next # split copied list from combined one
dummy = RandomListNode(0)
copied_current, current = dummy, head
while current:
copied_current.next = current.next
current.next = current.next.next
copied_current, current = copied_current.next, current.next
return dummy.next

C++:

class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head) return NULL;
RandomListNode *res = new RandomListNode(head->label);
RandomListNode *node = res;
RandomListNode *cur = head->next;
map<RandomListNode*, RandomListNode*> m;
m[head] = res;
while (cur) {
RandomListNode *tmp = new RandomListNode(cur->label);
node->next = tmp;
m[cur] = tmp;
node = node->next;
cur = cur->next;
}
node = res;
cur = head;
while (node) {
node->random = m[cur->random];
node = node->next;
cur = cur->next;
}
return res;
}
};

类似题目:

[LeetCode] 133. Clone Graph 克隆无向图

All LeetCode Questions List 题目汇总

  

[LeetCode] 138. Copy List with Random Pointer 拷贝带随机指针的链表的更多相关文章

  1. [LeetCode] 138. Copy List with Random Pointer 拷贝带有随机指针的链表

    A linked list is given such that each node contains an additional random pointer which could point t ...

  2. [leetcode]138. Copy List with Random Pointer复制带有随机指针的链表

    public RandomListNode copyRandomList(RandomListNode head) { /* 深复制,就是不能只是复制原链表变量,而是做一个和原来链表一模一样的新链表, ...

  3. [LeetCode] Copy List with Random Pointer 拷贝带有随机指针的链表

    A linked list is given such that each node contains an additional random pointer which could point t ...

  4. 力扣——Copy List with Random Pointer(复制带随机指针的链表) python实现

    题目描述: 中文: 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点. 要求返回这个链表的深拷贝. 示例: 输入:{"$id":" ...

  5. 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 ...

  6. Java for LeetCode 138 Copy List with Random Pointer

    A linked list is given such that each node contains an additional random pointer which could point t ...

  7. leetcode 138. Copy List with Random Pointer ----- java

    A linked list is given such that each node contains an additional random pointer which could point t ...

  8. [Leetcode] Copy list with random pointer 对带有任意指针的链表深度拷贝

    A linked list is given such that each node contains an additional random pointer which could point t ...

  9. leetcode 138. Copy List with Random Pointer复杂链表的复制

    python代码如下: # Definition for singly-linked list with a random pointer. # class RandomListNode(object ...

随机推荐

  1. PAT甲级1010踩坑记录(二分查找)——10测试点未过待更新

    题目分析: 首先这题有很多的坑点,我在写完之后依旧还有第10个测试点没有通过,而且代码写的不优美比较冗长勿喷,本篇博客用于记录写这道题的一些注意点 1.关于两个不同进制的数比大小一般采用将两个数都转化 ...

  2. Kotlin函数与Lambda表达式深入

    Kotlin函数: 关于Kotlin函数在之前也一直在用,用fun来声明,回忆下: 下面再来整体对Kotlin的函数进行一个学习. 默认参数(default arguments): 先来定义一个函数: ...

  3. Alpha冲刺(8/10)——2019.5.1

    所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(8/10)--2019.5.1 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪万 ...

  4. 2019牛客暑期多校训练营(第三场)G: Removing Stones(启发式分治)

    题意:给定N,表示N堆石子,每堆石子数为a[],问多少个区间,可以满足“石子总和若为偶数,那么可以两两取来自不同堆的石子,直到取完: 如果为奇数,那么排除其中一个,然后可以两两取来自不同堆的石子,直到 ...

  5. C# Base64字符串生成图片

    C# Base64字符串生成图片: //签字图片Base64格式去除开头多余字符data:image/png;base64, strSignImg = strSignImg.Substring(str ...

  6. Win如何查看某个端口被谁占用并停掉

    第一步在我们的电脑上按win+R键打开运行,输入cmd, 第二步进去命令提示符之后,输入“netstat -ano”,按回车键,查出所有端口,如下图所示: 第三步如果我们想找8089端口,输入nets ...

  7. H5视频播放小结(video.js不好用!!!)

    近期在做一个H5的视频课堂,遇到了H5播放的需求,因为原生的video的样式不太理想,尤其是封面无法压住控制条,这就需要我们自定义播放控件. 于是,找了很近的插件,找到了用户比较多的video.js插 ...

  8. openjdk k8s port-forward 连接容器jmx服务

    jmx 是java 自带的,如果需要使用我们只需要添加对应的配置即可,以下演示docker 集成jmx 使用kompose 生成k8s 的部署文件,使用port-forward 进行连接,所以java ...

  9. box-sizing 盒子模型

    一.概念 ①外加模式: box-sizing: content-box 这是由 CSS2.1 规定的宽度高度行为.宽度和高度分别应用到元素的内容,在宽度和高度之外绘制元素的内边距,即宽和高不包括内边距 ...

  10. 干货 | 10分钟掌握branch and cut(分支剪界)算法原理附带C++求解TSP问题代码

    00 前言 branch and cut其实还是和branch and bound脱离不了干系的.所以,在开始本节的学习之前,请大家还是要务必掌握branch and bound算法的原理. 01 应 ...