题目描述
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
解题思路
因为random指向随机,所以复制过程中可能random指向的节点还没被建立,故需要向整体复制所有节点才能避免野指针。
通过HashMap建立旧链表和新链表的映射,先复制其val值,然后迭代/递归复制next指向,最后再复制其随机指向。
解法
迭代法
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
HashMap<Node, Node> hm = new HashMap<>();
public Node copyRandomList(Node head) {
Node cur = head;
while(cur != null) {
hm.put(cur,new Node(cur.val));
cur = cur.next;
}
cur = head;
while(cur!=null) {
hm.get(cur).next = hm.get(cur.next);
hm.get(cur).random = hm.get(cur.random);
cur = cur.next;
}
return hm.get(head);
}
}
递归法
class Solution {
HashMap<Node, Node> hm = new HashMap<>();
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Node cur = head;
Node newN = new Node(cur.val);
if(!hm.containsKey(cur)) {
hm.put(cur, newN);
newN.next = copyRandomList(cur.next); //复制下一个位置
newN.random = hm.get(cur.random); //复制随机指向
}
return hm.get(cur);
}
}