138. Copy List with Random Pointer

Posted jamieliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了138. Copy List with Random Pointer相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

138. Copy List with Random Pointer

138. Copy List with Random Pointer

138 Copy List with Random Pointer

138. Copy List with Random Pointer

138. Copy List with Random Pointer(js)

138. Copy List with Random Pointer