HashMap 一步到位
复杂链表的复制
http://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba
//保存原链表节点和复制链表节点的对应
HashMap<RandomListNode, RandomListNode> hashMap = new HashMap<>();
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null)
return null;
RandomListNode randomListNode = new RandomListNode(pHead.label);
hashMap.put(pHead, randomListNode);
//移动的指针
RandomListNode temp = randomListNode ;
RandomListNode cur = pHead;
while (cur != null) {
//为next 节点赋值
if (cur.next != null) {
if (!hashMap.containsKey(cur.next))
hashMap.put(cur.next, new RandomListNode(cur.next.label));
temp.next = hashMap.get(cur.next);
}
//为random 节点赋值
if (cur.random != null) {
if (!hashMap.containsKey(cur.random))
hashMap.put(cur.random, new RandomListNode(cur.random.label));
temp.random = hashMap.get(cur.random);
}
//移动指针
cur = cur.next;
temp = temp.next;
}
return randomListNode;
}
查看9道真题和解析
顺丰集团工作强度 350人发布
