给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
按照通常的链表拷贝方式来处理,麻烦的地方在于随机指针的处理,要找到原链表结点上随机指针指向的结点在新表中的位置
解决的思路是
使用三次循环
第一次循环,拷贝全部结点,并将新结点插入原结点之后.
第二次循环,遍历全部结点,拷贝random指针
伪代码描述
A->random != null
A”->random=A->random->next
第三次循环,恢复原链表和拷贝的新链表
A->next=A’->next;
A’->next=A’->next->next;
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
// write your code here
RandomListNode p = head;
//复制结点并且插入原链表
while(p != null) {
RandomListNode q = new RandomListNode(p.label);
q.next = p.next;
p.next = q;
p = q.next;
}
p = head;
while(p != null) {
if(p.random != null)
p.next.random = p.random.next;
else
p.next.random = null;
p = p.next.next;
}
p = head;
RandomListNode q = head.next;
result = head.next;
//恢复
while(q.next != null) {
p.next = q.next;
p = p.next;
q.next = p.next;
q = q.next;
}
return result;
}
}