题目描述

思路详解:
这道题我想的是用map这种key-value键值对来建立节点之间的映射关系
- 首先判断参数的合法性,如果pHead为空,则直接返回null
- 然后将pHead中所有节点保存到map中
- 最后对链表进行建立映射关系,完成深拷贝即可
代码如下:
import java.util.*;
class RandomListNode{
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
//判断链表是否为空,为空则直接返回null
if (pHead == null){
return null;
}
//定义一个变量用来存储复制后的链表的头
RandomListNode newHead = new RandomListNode(pHead.label);
RandomListNode tmp = newHead;
RandomListNode cur = pHead;
Map<RandomListNode,RandomListNode> map = new HashMap<>();
//将pHead中的节点都存到map中去
while (pHead != null){
map.put(pHead,new RandomListNode(pHead.label));
pHead = pHead.next;
}
while (cur != null){
tmp.next = map.get(cur.next);
tmp.random = map.get(cur.random);
cur = cur.next;
tmp = tmp.next;
}
return newHead;
}
}
1297

被折叠的 条评论
为什么被折叠?



