请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
剑指 Offer 35. 复杂链表的复制 - 力扣(LeetCode) (leetcode-cn.com)
//遍历链表,创建新链表中对应的节点,并把原链表节点和对应的新链表节点放入哈希表
//再遍历原链表,构建新链表节点的next和random指向
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
Map<Node, Node> map = new HashMap();
Node temp = head;
while(temp != null){
map.put(temp, new Node(temp.val));
temp = temp.next;
}
temp = head;
while(temp != null){
map.get(temp).next = map.get(temp.next);
map.get(temp).random = map.get(temp.random);
temp = temp.next;
}
return map.get(head);
}
}
//遍历链表,每构建一个新的节点就把它插入原节点的后面,
//新节点的random指向它的前一个结点(也就是原结点)的random指向的后一个结点
//把链表拆分成原链表和新链表
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return head;
}
Node temp = head;
while(temp != null){
Node n = new Node(temp.val);
n.next = temp.next;
temp.next = n;
temp = n.next;
}
temp = head;
while(temp != null){
if(temp.random != null){
temp.next.random = temp.random.next;
}
temp = temp.next.next;
}
temp = head;
Node res = head.next;
Node newHead = head.next;
while(res.next != null){
temp.next = temp.next.next;
res.next = res.next.next;
res = res.next;
temp = temp.next;
}
temp.next = null;
return newHead;
}
}