題意
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Subscribe to see which companies asked this question.
解法
回頭補上
實現
/**
* 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:
RandomListNode *splitCopyList(RandomListNode* head){
RandomListNode* copyhead = head->next;
RandomListNode* cur = head;
while(cur != NULL){
RandomListNode* ccur = cur->next;
cur->next = ccur->next;
if(cur->next != NULL) ccur->next = cur->next->next;
else ccur->next = NULL;
cur = cur->next;
}
return copyhead;
}
RandomListNode *copyRandomRela(RandomListNode* head){
RandomListNode* cur = head;
while(cur != NULL){
RandomListNode* random = cur->random;
RandomListNode* ccur = cur->next;
if(random != NULL){
ccur->random = random->next;
}
cur = ccur->next;
}
return head;
}
RandomListNode *copyNextRela(RandomListNode* head){
RandomListNode* cur = head;
while(cur != NULL){
RandomListNode* ccur = new RandomListNode(cur->label);
ccur->next = cur->next;
cur->next = ccur;
cur = ccur->next;
}
return head;
}
RandomListNode *copyRandomList(RandomListNode *head) {
if(head == NULL) return head;
RandomListNode* nextHead = copyNextRela(head);
RandomListNode* randomHead = copyRandomRela(head);
RandomListNode* copyHead = splitCopyList(randomHead);
return copyHead;
}
};