剑指Offer 35 复杂链表的复制
这道题用两次for或者while循环时,有个需要注意的地方,需要特意在map里面添加键NULL和值NULL的对应关系,如果忘记添加这一语句,后面遇到有些结点的random指向NULL时,map.find()会找不到这个结点,然后返回值是map::end,这样就会会报错。另外需要注意用map.find返回的是一个iterator,要用 map.find()->second访问返回的值。以下是代码解答:
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { if(head==NULL)return NULL; Node *temphead=head; map<Node*,Node*>mymap; while(temphead!=NULL){ Node* newNode=new Node(temphead->val); mymap.insert(pair<Node*,Node*>(temphead,newNode)); temphead=temphead->next; } temphead=head; Node* newtemphead=mymap.find(head)->second; mymap.insert(pair<Node*,Node*>(NULL,NULL)); while(temphead!=NULL){ newtemphead->next=mymap.find(temphead->next)->second; newtemphead->random=mymap.find(temphead->random)->second; newtemphead=newtemphead->next; temphead=temphead->next; } return mymap.find(head)->second; } };