博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
138. Copy List with Random Pointer
阅读量:2351 次
发布时间:2019-05-10

本文共 1099 字,大约阅读时间需要 3 分钟。

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.

我的想法

在循环建立新链表的时候,用一个hashmap存入所有新建的点。再用一个循环遍历原链表,补充新链表的random结点。但是这样只能用于结点没有重复的val

class Solution {
public Node copyRandomList(Node head) {
if(head == null) {
return head; } HashMap
map = new HashMap<>(); Node res = new Node(head.val, null, null); Node resHead = res; map.put(resHead.val, resHead); Node temp = head.next; while(temp != null) {
Node node = new Node(temp.val, null, null); map.put(node.val, node); resHead.next = node; resHead = resHead.next; temp = temp.next; } resHead = res; while(head != null) {
if(head.random != null) {
resHead.random = map.get(head.random.val); } head = head.next; resHead = resHead.next; } return res; }}

解答

为了解决重复val的问题,hashmap的key应该是老的结点

转载地址:http://cyqvb.baihongyu.com/

你可能感兴趣的文章
阿里云+腾讯云采购季优惠攻略
查看>>
PCB设计容易出错的地方都有哪些?
查看>>
挠性电路板和刚性电路板的区别,以及柔性电路板焊接方法操作步骤
查看>>
如何做好一块PCB板,大神从以下几个方面做了论述
查看>>
学习笔记1之static
查看>>
学习笔记2之继承
查看>>
循环链表实现增、删、改、查等功能
查看>>
Android实现超链接和跑马灯
查看>>
实现二叉树先序、中序、后序遍历
查看>>
Socket客户端服务器连接
查看>>
简单字符设备驱动程序的操作步骤
查看>>
视频压缩:I帧、P帧、B帧
查看>>
视频编解码基础一
查看>>
视频编码学习二
查看>>
视频处理
查看>>
Python的安装教程
查看>>
谈谈码率、帧率、分辨率和清晰度
查看>>
OSI参考模型通信举例
查看>>
Vue.js 入门学习(一)
查看>>
Vue.js入门学习(二)实例、数据绑定、计算属性
查看>>