138. Copy List with Random Pointer

Description

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.

Solution

HashMap, time O(n), space O(n)

跟clone graph不同的是,这道题里面的label不是unique的,所以不能用label做key,只能用原始的node做key。为了保证指向的节点存在,需要两次遍历,第一次遍历clone所有节点,第二次遍历将节点们连起来。

/**
 * 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 map = new HashMap<>();
        // copy all the nodes
        RandomListNode curr = head;
        while (curr != null) {
            map.put(curr, new RandomListNode(curr.label));
            curr = curr.next;
        }
        // assign next and random pointers
        curr = head;
        while (curr != null) {
            map.get(curr).next = map.get(curr.next);
            map.get(curr).random = map.get(curr.random);
            curr = curr.next;
        }
        
        return map.get(head);
    }
}

你可能感兴趣的:(138. Copy List with Random Pointer)