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.

Note:
You must return the copy of the given head as a reference to the cloned list.


思路一:哈希Map(Java)

class LinearSpaceApproach {

  public RandomListNode copyRandomList(RandomListNode head) {

    if (head == null) {
      return null;
    }
    
    Map<RandomListNode, RandomListNode> cloneMap = new HashMap<RandomListNode, RandomListNode>();
    
    RandomListNode curr = head;
    while (curr != null) {
      cloneMap.put(curr, new RandomListNode(curr.val));
      curr = curr.next;
    }
    
    curr = head;
    while (curr != null) {

      cloneMap.get(curr).next = cloneMap.get(curr.next);

      cloneMap.get(curr).random = cloneMap.get(curr.random);

      curr = curr.next;
    }
    
    return cloneMap.get(head);
  }

}

时间复杂度o(n),空间复杂度o(n)


思路二:Tricky one(C++)

class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if (head == NULL) return NULL;
        for (RandomListNode* cur = head; cur != nullptr; ) {
            RandomListNode* node = new RandomListNode(cur->val);
            node->next = cur->next;
            cur->next = node;
            cur = node->next;
        }

        for (RandomListNode* cur = head; cur != nullptr; ) {
            if (cur->random != NULL)
                cur->next->random = cur->random->next;
            else
                cur->next->random = NULL;
            cur = cur->next->next;
        }

        // 分拆两个单链表
        RandomListNode dummy(-1);
        for (RandomListNode* cur = head, *new_cur = &dummy;
                cur != nullptr; ) {
            new_cur->next = cur->next;
            new_cur = new_cur->next;
            cur->next = cur->next->next;
            cur = cur->next;
        }
        return dummy.next;
    }
};

时间复杂度o(n),空间复杂度o(1)


参考来源: