【剑指35】复杂链表的复制

方法一:先链接再分离,时间O(n),空间O(n)

题解:

  • 复制每个节点,并将之链接到原链表中
  • 调整 random 节点指向,random的下一个节点(random不空)
  • 分离链表
/*
// 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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45691748/article/details/114636697
今日推荐