findingsea's Studio.

Copy List with Random Pointer@LeetCode

Word count: 251 / Reading time: 1 min
2015/04/25 Share

Copy List with Random Pointer

节点中需要拷贝的两个引用是nextrandomnext引用比较好拷贝,相当直接复制普通列表。而对于random则需要目标节点已存在才比较容易些拷贝代码,采用的办法就是构造一个HashMap,其中key是原节点,value是拷贝节点,在拷贝random引用的过程中,直接用map.get(node.random)来获取相应的目标节点即可。

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 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) {
if (head == null)
return null;
RandomListNode targetNode = head, copyPreHead = new RandomListNode(-1), copyNode = copyPreHead;
HashMap<RandomListNode, RandomListNode> copiedMap = new HashMap<RandomListNode, RandomListNode>();
while (targetNode != null) {
copyNode.next = new RandomListNode(targetNode.label);
copiedMap.put(targetNode, copyNode.next);
targetNode = targetNode.next;
copyNode = copyNode.next;
}
targetNode = head;
copyNode = copyPreHead.next;
while (targetNode != null) {
if (targetNode.random != null) {
copyNode.random = copiedMap.get(targetNode.random);
}
targetNode = targetNode.next;
copyNode = copyNode.next;
}
return copyPreHead.next;
}
}
CATALOG
  1. 1. Copy List with Random Pointer