Leetcode232: Copy List with Random Pointer

来源:互联网 发布:windows rt 编辑:程序博客网 时间:2024/05/10 14:35

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.

网上看到一个O(n)的算法,非常巧妙的利用了原来链表的信息:

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


0 0