1. 程式人生 > >leetcode之有隨機指標的連結串列深拷貝

leetcode之有隨機指標的連結串列深拷貝

題目:

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.

思路:

如果沒有random pointer那是極容易的,順著連結串列走讀一遍 ,逐個拷貝節點並連結即可,有了random pointer後,其實也就是加上了記錄random pointer的關係而已,考慮到random pointer可以往前指,也可以往後指,則必須全部遍歷完才能完整地建立起random pointer對應關係表,記錄對應關係,當然用map的資料結構啦,c++不太熟,查了下文件也不難寫這麼個基本的資料結構,用兩個map,一個儲存原始連結串列的random指向,另一個記錄原始連結串列和新建連結串列按照節點順序建立的對應關係,這樣在走讀完原始連結串列所有節點後,再刷一遍兩個map就可以恢復新建連結串列中與原始連結串列random指向對應的random 指標了,為了省空間,當然map的元素都用

int*表示

程式碼:

/**
 * 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;
        }
        std::map<RandomListNode*, RandomListNode*> parall;
        std::map<RandomListNode*, RandomListNode*> randpoint;

        RandomListNode * pleft=head;
        RandomListNode * copyList=new RandomListNode(pleft->label);
        
        RandomListNode * pright=copyList;
        parall.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pright));
        randpoint.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pleft->random));
        pleft=pleft->next;
        while(pleft!=NULL)
        {
           //create corresponding node
            RandomListNode* tmpRight=new RandomListNode(pleft->label);
            pright->next=tmpRight;
            pright=pright->next;
            
            parall.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pright));
 
            randpoint.insert(std::pair<RandomListNode*,RandomListNode*>(pleft,pleft->random));
 
            pleft=pleft->next;
        }

        for( std::map<RandomListNode*, RandomListNode*>::iterator ii=randpoint.begin(); ii!=randpoint.end(); ++ii)
        {
           if((*ii).second!=NULL)
           {
               parall[(*ii).first]->random=parall[(*ii).second];
           }
        }
        
        return copyList;
    }
};