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.

思路:第一遍正常复制链表,同一时候用哈希表保存链表中原始节点和新节点的相应关系,第二遍遍历链表的时候,再复制随机域。

这是一种典型的空间换时间的做法,n个节点,须要大小为O(n)的哈希表,同一时候时间复杂度能够减少到O(n)。

/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return head;
}
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode res = null;
RandomListNode taiListNode = null;
RandomListNode cur = head;
while (cur != null) {
if (res == null) {
res = new RandomListNode(cur.label);
res.next = res.random = null;
taiListNode = res;
map.put(head, res);
}
else{
taiListNode.next = new RandomListNode(cur.label);
taiListNode = taiListNode.next;
map.put(cur, taiListNode); }
cur = cur.next;
}
taiListNode.next = null;
cur = head;
taiListNode = res;
while (cur != null) {
taiListNode.random = (RandomListNode)map.get((RandomListNode)cur.random);
cur = cur.next;
taiListNode = taiListNode.next;
}
return res;
}
}

最新文章

  1. 从零开始编写自己的C#框架(19)——Web层后端权限模块
  2. java代码解压zip文件
  3. 使用ABP时报错“UPDATE 语句与 FOREIGN KEY SAME TABLE 约束&quot;FK_dbo.AbpUsers_dbo.AbpUsers_LastModifierUserId&quot;冲突”的解决办法
  4. 【转】SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
  5. IOS 入门开发教程
  6. 杭电1241 Oil Deposits
  7. 使用 JavaScript
  8. web安全之token
  9. [Irving]DateTime格式处理大全
  10. 关于FPGA异步时钟采样--结绳法的点点滴滴
  11. LeetCode_3 sum closet
  12. linux查看用户登录信息-w命令
  13. C#区域截图&mdash;&mdash;调用API截图
  14. jq常用事件(on,blur,focus,change),js/jq等待图片(页面)加载完毕事件,js读取文件
  15. Linux 的umask详解
  16. C++11-->单生产者,单消费者问题
  17. docker镜像的常用操作
  18. SpringBoot里使用RMI进行远程方法调用
  19. 用scp命令来通过ssh传输文件,ssh推送.py程序到CentOS7服务器端出现lost connection错误
  20. 8.17 一个博客demo

热门文章

  1. [Objective-C A]-知识点锦集
  2. 学会使用简单的MySQL操作
  3. Random.org -- 真正的随机数生成器
  4. mac 使用apache开启https功能,实现ios局域网内测(二)
  5. Asp.Net MVC项目通过Git同步到新开发设备上后无法作为网站启动
  6. Memcached 测试
  7. JavaScript点击按钮显示 确认对话框
  8. 2012全球SEO行业调查报告
  9. IOS使用Charts
  10. zookeeper程序员指南