MrainW's Home

All things come to those who wait!

0%

LeetCode 138. Copy List with Random Pointer

Question

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

https://leetcode.com/problems/copy-list-with-random-pointer/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public Node copyRandomList(Node head) {
Map<Node, Node> map = new HashMap<>();
for(Node cur = head; cur != null; cur = cur.next)
map.put(cur, new Node(cur.val));
for (Node cur = head; cur != null; cur = cur.next){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
}
return map.get(head);
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels