1.复制next节点,直接接在对应的原始节点之后;
2.复制random指针,该节点的random即该节点对应的原始节点的random的next;
3.拆分原始节点和复制节点,按照next指针遍历,奇数的为原始,偶数的为复制
java 代码
/**
* Definition for singly-linked list with a random pointer.
* class ListNode {
* int val;
* ListNode next, random;
* ListNode(int x) { this.val = x; }
* };
*/
class Solution {
public ListNode copyRandomList(ListNode head) {
if(head == null) return null;
ListNode r = head;
//复制原始节点,插在对应原始节点之后
while(r!=null){
ListNode t = new ListNode(r.val);
t.next = r.next;
r.next = t;
r = t.next;
}
//复制random节点,原始节点的下一个节点为复制节点,要想找该节点的random的复制,就要找原始节点random的下一个
r = head;
while(r!=null){
if(r.random!=null)
r.next.random = r.random.next;
r = r.next.next;
}
//拆分
ListNode re = head.next;
ListNode q = re;
r = head;
while(q.next!=null){
r.next = q.next;
r = r.next;
q.next = r.next;
q = q.next;
}
return re;
}
}