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);
 
    }
}

 

posted @ 2019-02-02 21:29  JamieLiu  阅读(80)  评论(0编辑  收藏  举报