指针的深拷贝。
来回用两次map即可在nlogn的时间复杂度下解决该问题。
class Solution { public: RandomListNode <em>copyRandomList(RandomListNode *head) { int length = getRandomList(head);<br /> if(length == 0) return NULL; int index = 0; RandomListNode * headb1 = head; map<RandomListNode</em>,int>map_ri; map_ri.clear(); while(head != NULL) { map_ri.insert(map<RandomListNode<em>,int>::value_type(head,index++)); head = head->next; } int *pos = new int[length]; map<RandomListNode</em>,int>::iterator itri; index = 0; head = headb1; while(head != NULL) { itri = map_ri.find(head->random); if(itri == map_ri.end()) pos[index++] = -1; else pos[index++] = itri->second; head = head->next; } head = headb1; map<int,RandomListNode <em>>map_r; map_r.clear(); index = 0; RandomListNode *copy = new RandomListNode(head->label); RandomListNode *copymove = copy; map_r.insert(map<int,RandomListNode</em>>::value_type(index++,copymove)); head = head->next; while(head!=NULL) { RandomListNode * tmp = new RandomListNode(head->label); copymove->next = tmp; copymove = copymove->next; map_r.insert(map<int,RandomListNode<em>>::value_type(index++,copymove)); head=head->next; } copymove = copy; index = 0; while(copymove != NULL) { map<int,RandomListNode</em>>::iterator it = map_r.find(pos[index++]); if(it == map_r.end()) copymove->random = NULL; else copymove ->random = it->second; copymove = copymove->next; } return copy; } private: int getRandomList(RandomListNode *head) { int length = 0; while(head != NULL) { head = head->next; length++; } return length; } };