Java实现复杂链表的复制
过程很简单,直接上代码
import java.util.HashMap;
import java.util.Map;
public class Solution {
/**
* 复杂链表复制
* @param pHead
* @return
*/
public RandomListNode Clone(RandomListNode pHead) {
Map<RandomListNode,RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode currentNode = pHead;
// 复制节点中的属性
while (currentNode != null) {
map.put(currentNode, new RandomListNode(currentNode.label));
currentNode = currentNode.next;
}
// 复制节点中的关系
currentNode = pHead;
while (currentNode != null) {
map.get(currentNode).next = map.get(currentNode.next);
map.get(currentNode).random = map.get(currentNode.random);
currentNode = currentNode.next;
}
return map.get(pHead);
}
}