Sword Finger Offer Series Sword Finger Offer 35: Copy of Complex Linked List: A very clever question, highly recommended

Title description:

Please implement the copyRandomList function to copy a complex linked list. In a complex linked list, each node has a next pointer to the next node, and a random pointer to any node or null in the linked list.

Example 1:

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0], [11,4],[10,2],[1,0]]

Example 2:

Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]

Example 3:

Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]

Example 4:

Input: head = []
Output: []
Explanation: The given linked list is empty (null pointer), so null is returned.

Problem-solving ideas:

The idea of ​​this question is very clever. My feeling is that each of the data he gave has two data, and the second number is confusing. This data has no effect, and it is impossible to find this data with code.

Therefore, you need to use other methods to replace this data when solving the problem:

  1. Copy each node first and place it behind the node
  2. At this time, according to the random of each node in the original linked list, find the random of the copied node. (This step is the key)
  3. Separate the copied node and return

Needless to say, the first and third steps, here is how to obtain the second step, because it is almost a completely copied new node, so the random of the newly copied node y is the random next of the original node x;

As shown in the figure above, if the random of B points to A, then the random of B1 must point to A1;

The method of A1 is B->random->next, which is the value of B1->random.

Code:

/*
// 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) return NULL;
        Node *headx = head;
        //将每个节点复制到他后面
        while(headx)
        {
            auto x = new Node(headx->val);
            x->next = headx->next;
            headx->next = x;
            headx = x->next;
        }

        //将另一个指针也复制一次
        Node *heady = head;
        while(heady && heady->next)
        {
            if(heady->random)
                heady->next->random = heady->random->next;
            heady = heady->next->next;
        }

        //将两个分离
        Node *newhead = head->next;
        Node *headz = head;
        while(headz && headz->next)
        {
            Node *z = headz->next;
            headz->next = z->next;
            headz = z;
        }
        return newhead;
    }
};

 

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/110823410