请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
在原链表上进行复制后再拆分
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
Node cur = head;
while(cur != null){
Node temp = cur.next;
cur.next = new Node(cur.val);
cur.next.next = temp;
cur = temp;
}
cur = head;
while(cur != null && cur.next != null){
if(cur.random != null)
cur.next.random = cur.random.next;
cur = cur.next.next;
}
cur = head;
Node res = cur.next;
while(cur != null && cur.next != null && cur.next.next != null){
Node temp = cur.next;
cur.next = cur.next.next;
temp.next = temp.next.next;
cur = cur.next;
}
cur.next = null;
return res;
}
}