复杂链表的复制
复杂链表的复制
http://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba
import java.util.*;
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
if(pHead == null) {
return null;
}
HashMap<RandomListNode, RandomListNode> cloneMap = new HashMap<RandomListNode, RandomListNode>();
RandomListNode head = pHead;
//第一次遍历,用于生成新的RandomListNode
while(head != null) {
cloneMap.put(head, new RandomListNode(head.label));
head = head.next;
}
//第二次遍历,用于处理前后指针
RandomListNode head2 = pHead;
while(head2 != null) {
RandomListNode cloneHead = cloneMap.get(head2);
if(head2.next != null) {
cloneHead.next = cloneMap.get(head2.next);
}
if(head2.random != null) {
cloneHead.random = cloneMap.get(head2.random);
}
head2 = head2.next;
}
return cloneMap.get(pHead);
}
}