码迷,mamicode.com
首页 > 其他好文 > 详细

138. Copy List with Random Pointer

时间:2019-02-02 21:56:26      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:color   which   lin   point   ext   code   哈希表   map   his   

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.

 

想了好久才明白deep copy的含义在于新链表的next 和 random指针要指向新链表中的node,而单纯用“=”的话就会指向旧链表。

所以要用哈希表来将新旧node进行对应。

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

 

138. Copy List with Random Pointer

标签:color   which   lin   point   ext   code   哈希表   map   his   

原文地址:https://www.cnblogs.com/jamieliu/p/10349219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!