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

哈希

/*
// 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;
    }
};

猜你喜欢

转载自www.cnblogs.com/Trevo/p/12797896.html
今日推荐