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. Codeforces D. Little Elephant and Interval(思维找规律数位dp)

    题目描述: Little Elephant and Interval time limit per test 2 seconds memory limit per test 256 megabytes ...

  2. 加速Github访问

    Github 仓库的数据传输很慢,甚至可能导致仓库拉取失败.例如: remote: Enumerating objects: , done. remote: Counting objects: % ( ...

  3. linux 服务器配置 ASF 云挂卡

    关于社区打不开:https://github.com/zyfworks/AnotherSteamCommunityFix 下载asf:https://github.com/JustArchi/Arch ...

  4. ThinkPHP远程调用模块的操作方法 URL 参数格式

    * 远程调用模块的操作方法 URL 参数格式 [项目://][分组/]模块/操作 * @param string $url 调用地址 * @param string|array $vars 调用参数 ...

  5. node爬虫爬取中文时乱码问题 | nodejs gb2312、GBK中文乱码解决方法

    iconv需要依赖native库,这样一来,在一些不支持native模块安装的虚拟主机和windows平台上,我们还是无法安心处理GBK编码. 老外写了一个通过纯Javascript转换编码的模块 i ...

  6. java代码操作word模板并生成PDF

    这个博客自己现在没时间写,等后面有时间了,自己再写. 这中需求是在实际的项目开发中是会经常遇到的. 下面我们先从简单入手一步一步开始. 1.首先,使用word创建一个6行两列的表格. 点击插入-6行2 ...

  7. 浅谈C++编译原理 ------ C++编译器与链接器工作原理

    原文:https://blog.csdn.net/zyh821351004/article/details/46425823 第一篇:      首先是预编译,这一步可以粗略的认为只做了一件事情,那就 ...

  8. python - django 使用ajax将图片上传到服务器并渲染到前端

    一.前端代码 <!doctype html> <html lang="en"> <head> <meta charset="UT ...

  9. 持续集成学习4 jenkins常见功能

    一.节点选择 1.yum安装jdk yum install -y java-1.8.0 java-1.8.0-openjdk-devel 2.节点选择有三种方式 a.通过系统自带功能限制任务只能在这个 ...

  10. Python爬虫 | 多线程、多进程、协程

    对于操作系统来说,一个任务就是一个进程(Process),比如打开一个浏览器就是启动一个浏览器进程,打开一个记事本就启动了一个记事本进程,打开两个记事本就启动了两个记事本进程,打开一个Word就启动了 ...