标签:
非常巧妙的方法,不需要用map,只需要O(1)的额外存储空间,分为3步:
1. 先复制链表,但是这个复制比较特殊,每个新复制的节点添加在原节点的后面,相当于"加塞"
2. 根据原节点的 ramdon 指针构造新节点的 random 指针
3. 恢复原链表结构,同时得到新复制链表
时间复杂度:O(n)
注意random有可能是NULL
代码:
1 RandomListNode *copyRandomList(RandomListNode *head) { 2 RandomListNode *h = NULL; 3 4 h = head; 5 while (h) { 6 RandomListNode *node = new RandomListNode(h->label); 7 node->next = h->next; 8 h->next = node; 9 h = h->next->next; 10 } 11 12 h = head; 13 while (h) { 14 h->next->random = h->random? h->random->next : NULL; 15 h = h->next->next; 16 } 17 18 h = head? head->next : NULL; 19 while (head) { 20 RandomListNode *tmp = head->next; 21 head->next = head->next->next; 22 tmp->next = head->next ? head->next->next : NULL; 23 head = head->next; 24 } 25 26 return h; 27 }
Leetcode#138 Copy List with Random Pointer
标签:
原文地址:http://www.cnblogs.com/boring09/p/4236001.html