[leetcode]Copy List with Random Pointer

带random随机指向链表任意地方的一个链表...

做深度拷贝.

先做next的拷贝,建立新链表.

然后把老链表的next指向新链表对应的等价节点,然后把这个新的节点的random指向老链表.

然后呢...很明显newListNode -> random -> random -> next

就是新链表random该指向的地方啦...

newListNode -> random = newListNode -> random -> random -> next;

然后再恢复oldlist的next链接...这里之前用map存好了...

好像还有一种不用map的做法

把新链表间接的插入到老链表之间...

/**
 * 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 == nullptr) return head;
        RandomListNode* dummy = new RandomListNode(-1);
        RandomListNode* tmp = head;
        RandomListNode* curr = dummy;
        unordered_map<RandomListNode* , RandomListNode*> lmap;
        //copy next
        while(tmp != nullptr){
            lmap[tmp] = tmp -> next;
            RandomListNode* node = new RandomListNode(tmp -> label);
            curr -> next = node;
            curr = node;
            tmp = tmp -> next;
        }
        
        tmp = dummy -> next;
        curr = head;
        
        //map
        while(curr != nullptr){
            RandomListNode* next = curr -> next;
            curr -> next = tmp;
            tmp -> random = curr;
            curr = next;
            tmp = tmp -> next;
        }
        
        curr = dummy -> next;
        while(curr != nullptr){
            curr -> random = curr -> random -> random == nullptr ? nullptr :  curr -> random -> random -> next;
            curr = curr -> next;
        }
        
        //restore
        tmp = head;
        while(tmp){
            tmp -> next = lmap[tmp];
            tmp = tmp -> next;
        }
        
        return dummy -> next;
        
    }
};

========update 03/08/2014======

之前因为看了某题解,还觉得很有道理。。。

但是既然你都map了为毛不做一个old到new的map就好了。。。

/**
 * 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) {
        unordered_map<RandomListNode*, RandomListNode*> old2new;
        RandomListNode* dummy = new RandomListNode(-1);
        RandomListNode* tmp = head;
        RandomListNode* curr = dummy;
        while (tmp) {
            RandomListNode* newNode = new RandomListNode(tmp->label);
            old2new[tmp] = newNode;
            curr->next = newNode;
            curr = curr -> next;
            tmp = tmp->next;
        }
        tmp = head;
        while (tmp) {
            if (tmp->random) {
                old2new[tmp]->random = old2new[tmp->random];
            }
            tmp = tmp-> next;
        }
        return dummy->next;
    }
};
原文地址:https://www.cnblogs.com/x1957/p/3493661.html