138. 複製帶隨機指針的鏈表

就是用回溯法。用一個hash_map來存儲訪問過的節點。

class Solution {

private:

    unordered_map<Node*, Node*> all;

public:

    Node* copyRandomList(Node* head) {

        if(head == NULL) return NULL;

        if(all.count(head) == 0) {

        all[head] = new Node(head->val);

        all[head]->next = copyRandomList(head->next);

        all[head]->random = copyRandomList(head->random);

        //return newNode;

        } 

        return all[head];  

    }

};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章