码迷,mamicode.com
首页 > 其他好文 > 详细

【剑指offer】【链表】35. 复杂链表的复制

时间:2020-04-28 22:51:41      阅读:49      评论:0      收藏:0      [点我收藏+]

标签:shm   优化   rand   int   solution   ret   val   node   efi   

哈希

/*
// 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) {
        if(!head) return head;

        unordered_map<Node*, Node*> hashmap;
        hashmap[NULL] = NULL;
        for(auto p = head; p; p = p -> next)
            hashmap[p] = new Node(p -> val);

        for(auto p = head; p; p = p -> next)
        {
            hashmap[p] -> next = hashmap[p -> next];
            hashmap[p] -> random = hashmap[p -> random];
        }
        return hashmap[head];
    }
};
*/
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(!head) return head;
        //使用哈希来做一个映射
        unordered_map<Node*, Node*> pos;

        pos[NULL] = NULL;
        //先复制正常的next节点,不复制random节点
        for(auto p = head; p; p = p -> next)
            pos[p] = new Node(p -> val);
        
        //复制指针的指向
        for(auto p = head; p; p = p -> next)
        {
            pos[p] -> next = pos[p -> next];
            pos[p] -> random = pos[p -> random];
        }
        return pos[head];
    }
};

优化

/*
// 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) {
        for(auto p = head; p;)
        {
            auto np = new Node(p -> val);
            auto next = p -> next;
            p -> next = np;
            np -> next = next;
            p = next;
        }

        for(auto p = head; p; p = p -> next -> next)
            if(p -> random)
                p -> next -> random = p -> random -> next;
        
        auto dummy = new Node(-1);
        auto cur = dummy;
        for(auto p = head; p; p = p -> next)
        {
            cur -> next = p -> next;
            cur = cur -> next;
            p -> next = p -> next -> next;
        }
        return dummy -> next;
    }
};

【剑指offer】【链表】35. 复杂链表的复制

标签:shm   优化   rand   int   solution   ret   val   node   efi   

原文地址:https://www.cnblogs.com/Trevo/p/12797896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!