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

这道题看答案了,哈希做法很不错。

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if (head == nullptr) return nullptr;
         
        Node* cur = head;
        unordered_map<Node*, Node*> map;
       
        while (cur != nullptr) {
            map[cur] = new Node(cur->val);
            cur = cur->next;
        }

        cur = head;
        while (cur != nullptr) {
            map[cur]->next = map[cur->next];
            map[cur]->random = map[cur->random];
            cur = cur->next;
        }

        return map[head];
    }
};

猜你喜欢

转载自blog.csdn.net/jcl314159/article/details/119672945
今日推荐