leetcode 138. 复制带随机指针的链表

https://leetcode-cn.com/problems/copy-list-with-random-pointer/

map法:

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if (head == NULL) return NULL;
        
        map node_map;
        Node *new_head =  new Node(head->val, head->next, head->random);
        node_map[head] = new_head;
        Node *prev = new_head;
        Node *cur = head->next;
        while(cur)
        {
            Node *new_node =new Node(cur->val, cur->next, cur->random);
            node_map[cur] = new_node;
            prev->next = new_node;
            prev = new_node;
            cur = cur->next;
        }
        cur = new_head;
        while(cur)
        {
            cur->random = node_map[cur->random];
            cur = cur->next;
        }
        return new_head;
    }
};

O(1)空间法:

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if (head == NULL) return NULL;
        
        Node *cur = head;
        while(cur)
        {
            Node *new_node =new Node(cur->val, cur->next, cur->random);
            new_node->next = cur->next;
            cur->next = new_node;
            cur = new_node->next;
        }
        
        cur = head;
        while(cur)
        {
            if (cur->random)
                cur->next->random = cur->random->next;
            cur = cur->next->next;
        }
        Node *ret = head->next;
        cur = head;
        while(cur)
        {
            Node *next = cur->next;
            cur->next = next->next;
            cur = cur->next;
            if (next->next)
                next->next = cur->next;            
            
        }
        return ret;
    }
};

 

你可能感兴趣的:(leetcode,面试算法)