Problem
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.
思路一(hashtable)
- hashtable 存每个listnode作为key, 对应的copy作为value
- 遍历旧节点, 建立新节点间的关系
- 时间复杂度 O(n)
- 空间复杂度 O(n)
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode curt = head;
while (curt != null) {
RandomListNode newNode = new RandomListNode(curt.label);
map.put(curt, newNode);
curt = curt.next;
}
curt = head;
while (curt != null) {
map.get(curt).next = map.get(curt.next);
map.get(curt).random = map.get(curt.random);
curt = curt.next;
}
return map.get(head);
}
思路二(two pointers)
- 建立所有next的点
- 关键: 如何解决不知道random在哪里
- 1 -> 1' -> 2 -> 2'
- 这样就知道了
- 时间复杂度 O(n)
- 空间复杂度 O(1)
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
RandomListNode curt = head;
while (curt != null) {
RandomListNode next = curt.next;
curt.next = new RandomListNode(curt.label);
curt.next.next = next;
curt = curt.next.next;
}
curt = head;
while (curt != null) {
if (curt.random != null)
curt.next.random = curt.random.next;
curt = curt.next.next;
}
RandomListNode dummy = new RandomListNode(0);
RandomListNode node = dummy;
curt = head;
while (curt != null) {
node.next = curt.next;
node = node.next;
curt = curt.next.next;
}
return dummy.next;
}