目录
1 题目链接
https://www.nowcoder.com/exam/oj/ta?page=1&tpId=13&type=13
2 题目
3 思路 & 代码
两个方案思路差不多,一个使用链表中的label做map的key,一个是用整个节点作链表的key
方案一 HashMap<Integer, RandomListNode> map
-
先忽视链表的random域,按照label和next域创建一条新链表
-
在创建的同时,以label为键,node为值,将新创建的节点放入hashmap中
-
这时存入hashmap的node只有label这个属性有值,next和random都为null。不过,在创建下一个node时,上一个node的next就会被赋值。
-
再次遍历题目所给的链表,这次遍历是处理新链表的random域
-
依据链表的label值,以及节点random域指向节点的label值,在hashmap中查找与这两个label对应的两个节点,然后为新链表的random域赋值,赋值前需要判断原链表的random域是否为空
- 如果random有指向的节点,则直接赋值即可
-如果原链表的random域为null,那么新链表的random域也赋值为null(这步操作可以省略,因为在创建该节点时,next和random都已经赋值为null了)
import java.util.*;
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null) {
return null;
}
HashMap<Integer, RandomListNode> map = new HashMap<>();
RandomListNode tmp = pHead;
//记录新链表的头节点
RandomListNode head = new RandomListNode(-1);
//创建新链表时,不断移动的两个指针
RandomListNode pre = head;
RandomListNode node = null;
//处理next域,按照next域先把链表连起来
while (tmp != null) {
node = new RandomListNode(tmp.label);
pre.next = node;
pre = node;
map.put(node.label, node);
tmp = tmp.next;
}
//处理random域
tmp = pHead;
while (tmp != null) {
node = map.get(tmp.label);
if (tmp.random != null) {
node.random = map.get(tmp.random.label);
}
tmp = tmp.next;
}
return head.next;
}
}
方案二 HashMap<RandomListNode, RandomListNode> map
import java.util.*;
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null) {
return null;
}
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode tmp = pHead;
RandomListNode head = new RandomListNode(-1);
RandomListNode pre = head;
RandomListNode node = null;
//处理next域
while (tmp != null) {
node = new RandomListNode(tmp.label);
pre.next = node;
pre = node;
map.put(tmp, node);
tmp = tmp.next;
}
//处理random域
tmp = pHead;
while (tmp != null) {
node = map.get(tmp);
if (tmp.random != null) {
node.random = map.get(tmp.random);
}
tmp = tmp.next;
}
return head.next;
}
}