leetcode Copy List with Random Pointer

来源:互联网 发布:如何淘宝开企业店铺 编辑:程序博客网 时间:2024/05/19 03:20

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.

首先需要理解的是深拷贝是什么意思吧。深拷贝不只是单纯的换个名字,而是要重新构造,结构一样。看这个图就能理解这个算法的精髓了


/** * 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) {} * }; */ /* 该算法更为巧妙,不用保存原始链表的映射关系,构建新节点时,指针做如下变化,即把新节点插入到相应的旧节点后面:1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next,  new1->next = new1->next->next该算法时间复杂度O(N),空间复杂度O(1)*/class Solution {public:    RandomListNode *copyRandomList(RandomListNode *head) {        if(head==NULL) return NULL;        RandomListNode *old=head;        while(old!=NULL){            RandomListNode *add=new RandomListNode(old->label);            RandomListNode *temp=old->next;            old->next=add;            add->next=temp;            old=temp;        }        old=head;        while(old!=NULL){            if(old->random!=NULL){                old->next->random=old->random->next;            }            old=old->next->next;        }        RandomListNode *dummy=new RandomListNode(INT_MIN);        dummy->next=head;        RandomListNode *n=dummy;        old=head;        while(old!=NULL){            n->next=n->next->next;            old->next=old->next->next;            old=old->next;            n=n->next;        }        n->next=NULL;        return dummy->next;    }};


0 0
原创粉丝点击