面試題35. 複雜鏈表的複製 哈希表/思維

https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
在這裏插入圖片描述

思路一:藉助哈希表,建立新舊節點之間的映射即可。

/*
// 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==NULL)
            return NULL;
        unordered_map<Node*,Node*> m;
        Node *cur=head,*n;
        while(cur!=NULL)
        {
            n=new Node(cur->val);
            m[cur]=n;
            cur=cur->next;
        }
        cur=head;
        while(cur!=NULL)
        {
            n=m[cur];
            n->next=m[cur->next];
            if(cur->random!=NULL)
                n->random=m[cur->random];
            cur=cur->next;
        }
        return m[head];
    }
};

思路二:不花費額外的空間。首先在每個節點後面掛一個新的節點(複製),然後再次遍歷鏈表,這時候的randomrandom就比較好處理了。

/*
// 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==NULL)
            return NULL;
        Node *n,*cur=head,*nxt;
        while(cur!=NULL)
        {
            n=new Node(cur->val);
            nxt=cur->next;
            n->next=nxt;
            cur->next=n;
            cur=nxt;
        }
        cur=head;
        while(cur!=NULL)
        {
            nxt=cur->next;
            nxt->random=cur->random;
            if(nxt->random!=NULL)
                nxt->random=nxt->random->next;
            cur=cur->next;
            if(cur!=NULL)
                cur=cur->next;
        }
        Node *ans=head->next;
        cur=head,nxt=cur->next;
        while(cur!=NULL)
        {
            nxt=cur->next;
            cur->next=nxt->next;
            cur=cur->next;
            if(cur!=NULL)
                nxt->next=cur->next;
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章