题目如下:
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
参考链接:http://www.cnblogs.com/TenosDoIt/p/3387000.html
题目大意:深拷贝一个链表,链表除了含有next指针外,还包含一个random指针,该指针指向字符串中的某个节点或者为空。
节点定义为:
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
假设原始链表如下,细线表示next指针,粗线表示random指针,没有画出的指针均指向NULL:
算法1:我们在构建新链表的节点时,保存原始链表的next指针映射关系,并把指针做如下变化(蓝色为原始链表节点,紫红色为新链表节点):
然后在上图的基础上进行如下两步
1、构建新链表的random指针:比如new1->random = new1->random->random->next, new2->random = NULL, new3-random = NULL, new4->random = new4->random->random->next
2、恢复原始链表:根据最开始保存的原始链表next指针映射关系恢复原始链表
该算法时间空间复杂度均为O(N)
算法2:该算法更为巧妙,不用保存原始链表的映射关系,构建新节点时,指针做如下变化,即把新节点插入到相应的旧节点后面:
同理分两步
1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next
2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next, new1->next = new1->next->next
该算法时间复杂度O(N),空间复杂度O(1)
下面给出第二种算法的实现:
/**
* 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 {
public RandomListNode copyRandomList(RandomListNode head) {
return recover(random(copy(head)));
}
private RandomListNode copy(RandomListNode head){
RandomListNode p = head;
while(p != null){
RandomListNode q = new RandomListNode(p.label);
q.random = null;
RandomListNode temp = p;
p = p.next;
q.next = p;
temp.next = q;
}
return head;
}
private RandomListNode random(RandomListNode head){
RandomListNode oldnode = head;
if(head == null) return null;
RandomListNode newnode = head.next;
while(oldnode != null){
if(oldnode.random != null)
newnode.random = oldnode.random.next;
oldnode = newnode.next;
if(oldnode != null)
newnode = oldnode.next;
}
return head;
}
private RandomListNode recover(RandomListNode head){
RandomListNode oldnode = head;
if(head == null) return null;
RandomListNode newHead = head.next;
RandomListNode newnode = newHead;
while(oldnode != null){
oldnode.next = newnode.next;
oldnode = newnode.next;
if(oldnode != null){
newnode.next = oldnode.next;
newnode = oldnode.next;
}
}
return newHead;
}
}