【Jianzhi 35】Replication of complex linked lists

Method 1: Link first and then separate, time O(n), space O(n)

answer:

  • Copy each node and link it to the original linked list
  • Adjust the point of random node, the next node of random (random is not empty)
  • Separate linked list
/*
// 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) 
    {
    
    
        // 1.复制每一个节点到原链表中,最后再分离
        if (head == nullptr)
            return nullptr;
        Node* cur = head;
        while (cur)
        {
    
    
            Node* temp = new Node(cur->val);
            temp->next = cur->next;
            temp->random = cur->random;
            cur->next = temp;
            
            cur = temp->next;
        }
        cur = head;
        // 调整random节点
        while (cur)
        {
    
    
            if (cur->next->random)
                cur->next->random = cur->next->random->next;
            cur = cur->next->next;
        }
        // 分离链表
        cur = head;
        Node* phead = cur->next;
        while (cur)
        {
    
    
            Node* temp = cur->next;
            cur->next = temp->next;
            cur = cur->next;
            if (cur)
                temp->next = cur->next; 
        }
        return phead;
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/114636697