思路
《剑指Offer》#26
基本步骤是:
- 在每个节点后面,拷贝一个相同的节点:A->A’->B->B’…
- 拷贝随机节点,即A’->random是A->random->next
- 分离拷贝后的链表
代码
(脑抽了一下,break和continue打错,看了半天)
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: void makeNodeDup(RandomListNode* head){ //make copy of linked node while(head!=NULL){ RandomListNode* replica = new RandomListNode(head->label); replica->next = head->next; head->next = replica; head = replica->next; } } void copyRandomLink(RandomListNode* head){ //copy random link in new-generated replicas while(head != NULL){ if(head->random == NULL){ head = head->next->next; continue; } RandomListNode* replica = head->next; replica->random = head->random->next; head = replica->next; } } RandomListNode* detachReplica(RandomListNode* head){ RandomListNode* replicaHead = NULL; while(head != NULL){ RandomListNode* replica = head->next; if(replicaHead == NULL){ replicaHead = replica; } head->next = replica->next; if(replica->next != NULL){ replica->next = replica->next->next; } else { replica->next = NULL; } head = head->next; } return replicaHead; } RandomListNode *copyRandomList(RandomListNode *head) { makeNodeDup(head); copyRandomLink(head); return detachReplica(head); } };