leetcode_138复制带随机指针的链表
最初版,用原node的next指向新node,从尾部开始更新random,修改了原链表结构未通过
/* // 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 *node = new Node(head->val, nullptr, nullptr); head->next=node; node->next=copyRandomList(temp); if(head->random!=NULL){ node->random=head->random->next; } return node; } };
2.新链表random完成后修改回去,尾部开始指向就失效了,结果新链表的random会指向错误,未通过
/* // 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 *node = new Node(head->val, nullptr, nullptr); head->next=node; node->next=copyRandomList(temp); if(head->random!=NULL){ node->random=head->random->next; } head->next=temp; return node; } };
新旧链表如果按一对一指针映射必须增加辅助空间做map,参考
https://www.cnblogs.com/reynold-lei/p/3362614.html
将新旧链表二合一,这样就不用多余空间了。
3错版同二的错误,afteconnection必须在全部遍历完成后完成,否则同二一样。
/* // 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; } //preConnection Node *node = new Node(head->val, head->next, nullptr); head->next=node; copyRandomList(node->next); //randomConnection if(head->random!=NULL){ node->random=head->random->next; } //afterConnection head->next=node->next; if(node->next!=NULL){ node->next=node->next->next; } return node; } };
4通过版本,在完成一次递归遍历完所有节点后再拆分成两条链
/* // 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* node = pre_copyRandomList(head); //after_copyRandomList(head); Node* temp; while(head->next!=NULL){ temp=head->next; head->next=head->next->next; head=temp; } return node; } Node* pre_copyRandomList(Node* head) { if (head == NULL) { return NULL; } //preConnection Node *node = new Node(head->val, head->next, nullptr); head->next=node; pre_copyRandomList(node->next); //randomConnection if(head->random!=NULL){ node->random=head->random->next; } return node; } //void after_copyRandomList(Node* head) { // //afterConnection // if(head->next!=NULL){ // Node* node=head->next; // head->next=head->next->next; // after_copyRandomList(node); // } //} };