题目:
输入复杂链表如图,复制该链表。
思路:
如图。传统的做法是先复制next指针部分,然后对于每个节点的random部分,则需要遍历整个链表查找对应节点。时间复杂度为O(n.^2)。时间这里总结一种时间复杂度为O(n)空间复杂度为O(1)的方法。
第一步。简单复制next指针部分,并将拷贝节点和源节点链接一起。结果如下图:
第二步。遍历链表,遇到random指针非空的,则其对应拷贝节点,也就是他的下一节点的random应该指向当前节点random指向的下一节点。例如A指向C,则A*必然指向C*,以此类推。
第三步。拆分节点,偶数节点串接为拷贝链表,奇数节点串接为原链表。
代码:
typedef struct Tree{ Tree* next; Tree* random; }* node; node copy(node head){ if(!head) return NULL; //复制链表 node temp=head; node copyNode=NULL; while(temp){ copyNode=new Tree(); copyNode->next=temp->next; temp->next=copyNode; temp=copyNode->next; } //复制随机指针 temp=head; while(temp){ if(!temp->random) temp->next->random=temp->random->next; temp=temp->next->next; } //将偶数链表拆分出来连接到一起即为链表的拷贝,当然应该将奇数部分重新整理还原 temp=head; node copyHead=NULL; copyNode=copyHead=temp->next; temp->next=copyNode->next; temp=temp->next; while(temp){ copyNode->next=temp->next; copyNode=copyNode->next; temp->next=copyNode->next; temp=temp->next; } return copyHead; }