- 算法
迭代算法 - 核心思想
在每个结点后面做一个复制,然后复制每个结点的random,最后截断链表。 - 代码
class Solution {
public Node copyRandomList(Node head) {
Node firstHead = head;
Node secondHead = head;
while(firstHead != null){
Node temp = new Node(firstHead.val);
temp.next = firstHead.next;
firstHead.next = temp;
firstHead = firstHead.next.next;
}
while(secondHead != null){
if(secondHead .random != null){
secondHead.next.random = secondHead.random.next;
}
secondHead = secondHead.next.next;
}
Node result = new Node(0),cur = result;
for(Node p = head;p != null;p = p.next){
Node q = p.next;
cur.next = q;
cur = cur.next;
p.next = q.next;
}
return result.next;
}
}