剑指 Offer 35. 复杂链表的复制 LCOF
仅供自己学习
思路:
之前也做过复制链表的题,当时也是用的hash表将原链表作为key,将复制链表作为value一一映射,当所有的链表都存放在hash表后,就能很快速的找到下一个节点和random指向的节点。
为什么不直接复制后直接赋值,如果这样直接赋值,指向的不是复制的而是原链表的节点。如果遍历的时候还复制该节点指向的random的节点来给复制节点,那么到random这个节点赋值的时候,指向的又不是同一个了。
代码:
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 Node* next; 7 Node* random; 8 9 Node(int _val) { 10 val = _val; 11 next = NULL; 12 random = NULL; 13 } 14 }; 15 */ 16 class Solution { 17 public: 18 Node* copyRandomList(Node* head) { 19 if(head==NULL) return NULL; 20 Node* cur=head; 21 unordered_map<Node*,Node*> mp; 22 while(cur!=NULL){ 23 mp[cur]=new Node(cur->val); 24 cur=cur->next; 25 } 26 cur=head; 27 while(cur!=NULL){ 28 mp[cur]->next=mp[cur->next]; 29 mp[cur]->random=mp[cur->random]; 30 cur=cur->next; 31 } 32 return mp[head]; 33 } 34 };
还有一种是在原链表操作的方法,拼接和拆分。我们遍历原链表,在每个原链表节点添加复制节点,并将原链表节点指向这复制节点,当完成后再将复制节点的random指向,也能解决random指向的问题。当我们拆分的时候要将原链表还原,否则会报错。拆分的时候就是将原链表和复制链表分离出来,用一个指针指向复制链表的头节点,然后再用一个cur指针开始分离复制链表,用一个pre指针复原原链表。
代码:
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 Node* next; 7 Node* random; 8 9 Node(int _val) { 10 val = _val; 11 next = NULL; 12 random = NULL; 13 } 14 }; 15 */ 16 class Solution { 17 public: 18 Node* copyRandomList(Node* head) { 19 if(head==NULL) return NULL; 20 Node* cur=head; 21 while(cur!=NULL){ 22 Node* temp=new Node(cur->val); 23 temp->next=cur->next; 24 cur->next=temp; 25 cur= temp->next; 26 } 27 cur=head; 28 while(cur!=NULL){ 29 if(cur->random!=NULL) 30 cur->next->random=cur->random->next; 31 cur=cur->next->next; 32 } 33 Node* res=head->next; 34 cur=head->next; 35 Node* pre=head; 36 while(cur->next!=NULL){ 37 pre->next=pre->next->next; 38 cur->next=cur->next->next; 39 pre=pre->next; 40 cur=cur->next; 41 } 42 pre->next=NULL; 43 return res; 44 } 45 };

浙公网安备 33010602011771号