首先读懂题意,复制这个链码,难点在于random复制可能节点还未创建。
递归写法,所以是找到开头用if判断进入递归,而不是while无限循环。
/*
// 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 {
Map<Node,Node> map = new HashMap<Node,Node>();
public Node copyRandomList(Node head) {
if(head == null) return null;
if(!map.containsKey(head)){
Node headNew = new Node(head.val);
map.put(head,headNew);
headNew.next = copyRandomList(head.next);
headNew.random = copyRandomList(head.random);
}
return map.get(head);
}
}
链表复制法,先直接把每个节点复制一遍,然后给新节点的random赋值,这样不会超出节点范围
/*
// 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 {
public Node copyRandomList(Node head) {
if(head == null) return null;
Node cur = head;
while(cur != null){
Node tmp = new Node(cur.val);
tmp.next = cur.next;
cur.next = tmp;
cur = tmp.next;
}
cur = head;
while(cur != null){
if(cur.random != null){
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
cur = head.next;
Node pre = head;
Node res = head.next;
while(cur.next != null){
pre.next = pre.next.next;
cur.next = cur.next.next;
pre = pre.next;
cur = cur.next;
}
pre.next = null;
return res;
}
}