1. 程式人生 > >劍指Offer_編程題_25

劍指Offer_編程題_25

list tno off cond next ext 輸入 輸出 label

題目描述

輸入一個復雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果為復制後復雜鏈表的head。(註意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead == NULL){
            return NULL;
        }
        map<RandomListNode*,RandomListNode*>tmpMap;
        RandomListNode* p1 = NULL;
        RandomListNode* p2Head = NULL;
        RandomListNode* tmpHead = pHead;
        if(tmpHead){
            p1 = new RandomListNode(tmpHead->label);
            p2Head = p1;
            tmpMap[tmpHead] = p1;
            tmpHead = tmpHead->next;
        }
        while(tmpHead){
            RandomListNode* tmp = new RandomListNode(tmpHead->label);
            p1->next = tmp;
            p1 = tmp;
            tmpMap[tmpHead] = tmp;
            tmpHead = tmpHead->next;
        }
        tmpHead = pHead;
        map<RandomListNode*,RandomListNode*>::iterator it;
        map<RandomListNode*,RandomListNode*>::iterator it_random;
        while(tmpHead){
            if(tmpHead->random){
                it = tmpMap.find(tmpHead);
                if(it != tmpMap.end()){
                    it_random = tmpMap.find(tmpHead->random);
                    if(it_random != tmpMap.end()){
                        it->second->random = it_random->second;
                    }
                }
                
            }
            tmpHead = tmpHead->next;
        }
        return p2Head;
    }
};

  

劍指Offer_編程題_25