剑指 Offer 35. 复杂链表的复制

题目

剑指 Offer 35. 复杂链表的复制

我的思路

遍历两次:
第一次根据next指针,创建并拷贝next链。
第二次根据已有next链从前向后递进,依次查找每个节点的random指向节点的位置,并为指针赋值。看起来第二次遍历的时间复杂度较高,达到了n^2。也许可以借助辅助存储空间,以牺牲空间的代价换取效率的提升。在第一次遍历时建造两个哈希表,1.新链表的(节点序号,该节点的指针)2.旧链表(节点的指针,序号)

看了官方题解:其实还可以更简练,用一个哈希表存储旧节点和新节点的映射即可!

我的实现

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    Node* copyRandomList(Node* head) {
        Node* newhead = NULL;
        Node* oldtemp = NULL;
        Node* newtemp = NULL;
        unordered_map<int,Node*> NMAP;
        unordered_map<Node*,int> OMAP;
        //第一次遍历:拷贝next链;在第一次遍历时建造两个哈希表,1.新链表的(节点序号,该节点的指针)2.旧链表(节点的指针,序号)
        oldtemp = head;
        int no = 0;
        if(oldtemp!=NULL){
            newhead = new Node(oldtemp->val);
            OMAP.insert(make_pair(oldtemp,no));
            NMAP.insert(make_pair(no,newhead));
            newtemp = newhead;
            no++;
            while(oldtemp->next!=NULL){
                newtemp->next = new Node(oldtemp->next->val);

                OMAP.insert(make_pair(oldtemp->next,no));
                NMAP.insert(make_pair(no,newtemp->next));
                oldtemp = oldtemp->next;
                newtemp = newtemp->next;
                no++;
            }
        }
        OMAP[nullptr] = -1;
        NMAP[-1] = nullptr;


        //第二次遍历:
        oldtemp = head;
        newtemp = newhead;
        while(oldtemp!=NULL){
            newtemp->random = NMAP[OMAP[oldtemp->random]];


            oldtemp = oldtemp->next;
            newtemp = newtemp->next;
        }
        return newhead;

        
    }
};

时间复杂度On,遍历两次链表

空间复杂度也是On,用还有节点个数的哈希表来作为辅助变量。

拓展学习

原文地址:https://www.cnblogs.com/BoysCryToo/p/13516760.html