给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深拷贝。
做这道题分为三步:
假设我们要复制的链表如下:
橙色的为随机指针
- 遍历原链表的每一个结点,复制新结点,插到原链表的后边
- 遍历原链表的每一个节点,进行新结点random的设置
cur.next.random = cur.random.next;
- 把一条链表拆分为原链表和新链表
代码如下:
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
/**
* 1. 创建新结点插到老结点后边
* 2. 设置 random
* 3. 拆开
*/
// 第一步
Node cur = head;
while (cur != null) {
Node n = new Node(cur.val);
n.next = cur.next;
cur.next = n;
cur = cur.next.next;
}
// 第二步
cur = head;
while (cur != null) {
if (cur.random != null) {
cur.next.random = cur.random.next;
} else {
cur.next.random = null;
}
cur = cur.next.next;
}
// 第三步
cur = head;
Node rhead = head.next;
while (cur != null) {
Node n = cur.next;
cur.next = n.next;
if (n.next != null) {
n.next = n.next.next;
}
cur = cur.next;
}
return rhead;
}
}