138. Copy List with Random Pointer

栏目: Java · 发布时间: 6年前

内容简介: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.难度:medium

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.

难度:medium

题目:给定一链表其每个结点包含一随机指针可以指向任意一结点或是为空。

思路:hash map

Runtime: 2 ms, faster than 72.52% of Java online submissions for Copy List with Random Pointer.

Memory Usage: 38.5 MB, less than 100.00% of Java online submissions for Copy List with Random Pointer.

/**
 * 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) {
        Map<RandomListNode, RandomListNode> mrr = new HashMap<>();
        RandomListNode ptr = head;
        while (ptr != null) {
            mrr.put(ptr, new RandomListNode(ptr.label));
            ptr = ptr.next;
        }
        ptr = head;
        while (ptr != null) {
            RandomListNode node = mrr.get(ptr);
            node.next = mrr.get(ptr.next);
            node.random = mrr.get(ptr.random);
            ptr = ptr.next;
        }
        
        return mrr.get(head);
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

创新公司

创新公司

[美]艾德·卡特姆、埃米·华莱士 / 靳婷婷 / 中信出版社 / 2015-2 / 49.00元

●《玩具总动员》《海底总动员》《机器人瓦力》《飞屋环游记》等14部脍炙人口的动画长片, 近30次奥斯卡奖, 7部奥斯卡最佳动画长片,7次金球奖; ●几乎每一部电影一上映都位居票房榜首,所有电影都曾进入影史票房总榜前50,每一部电影都是商业与艺术的双赢。 ●即便新兴动画公司不断涌现,皮克斯始终保持动画界的王者之位,这一切背后的秘密就在于:不断推动创新的创意管理方式。 你可以从本书......一起来看看 《创新公司》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具