- 题目 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的 深拷贝。
我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
val:一个表示 Node.val 的整数。 random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
-
思路
- 拷贝节点形成旧-新-旧-新的链表
- 设置新的节点的 random 指针
- 将旧-新-旧-新链表拆分
-
代码
class Solution {
func copyRandomList(_ head: Node?) -> Node? {
if head == nil { return head }
// 拷贝节点形成旧-新-旧-新的链表
var cur = head
while cur != nil {
let node = Node(cur!.val)
node.next = cur?.next
cur?.next = node
cur = node.next
}
// 设置新的节点的 random 指针
cur = head
while cur != nil {
cur?.next?.random = cur?.random?.next
cur = cur?.next?.next
}
var oldList = head
var newList = head?.next
let newHead = head?.next
// 将旧-新-旧-新链表拆分
while oldList != nil {
oldList?.next = oldList?.next?.next
newList?.next = newList?.next?.next
oldList = oldList?.next
newList = newList?.next
}
return newHead
}
}