LeetCode: Copy List with Random Pointer

来源:互联网 发布:网络电影播放器 编辑:程序博客网 时间:2024/06/08 12:28

Copy List with Random Pointer


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.

耗时:104ms。


算法步骤:

  1.  将现有List复制一份到原有List, 即形成 A -> A' -> B -> B' -> .......的形式。 这样可以方便处理random节点的情况,假设A指向X, 如果分别创建两个链表,则需要O(N)的时间复杂度使得A' 指向 X'。但是如果建立上述结构,则可以在O(1)的时间内完成。即为:A->next->random = X->next;
  2. 将链表 A -> A' -> B -> B' -> .......断开,形成两条链表 A->B->... 和A'->B'->....

代码实现:
/** * 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 *copyRandomList(RandomListNode *head) {                if(head == NULL)//exception            return NULL;                //copy all next node in the list           RandomListNode* t = head;        while(t != NULL)        {            RandomListNode* tnext = t->next;            RandomListNode* newt = new RandomListNode(t->label);            t->next = newt;            newt->next = tnext;            t = tnext;        }                //copy all random node in the list         t = head;        while(t!=NULL)        {            if(t->random != NULL)            {                t->next->random = t->random->next;               }            t = t->next;            t = t->next;        }                        //spilt the list to result.        RandomListNode* copyHead = head->next;;        RandomListNode* copyt = copyHead;        t = head;                while(t!=NULL)        {            //delete t->next;            t->next = t->next->next;            if(copyt->next != NULL)                 copyt->next = copyt->next->next;                        t = t->next;            copyt = copyt->next;        }                return copyHead;    }};

0 0
原创粉丝点击