JZ25 deep copy of complex linked list

Title Description
Input a complex linked list (each node has a node value and two pointers, one points to the next node, and the other special pointer random points to a random node), please make a deep copy of this linked list, and return the copied head node. (Note, please do not return the node reference in the parameter in the output result, otherwise the judging program will return empty directly)

Solution: There are some problems in the implementation of this topic, so I refer to Niuke’s implementation and find that the idea is quite simple. The implementation process is mainly completed by creating a new linked list in the existing linked list. The specific implementation process is analyzed as follows :
insert image description here
After analyzing the implementation process clearly, the code implementation is relatively easy. The specific code is as follows:

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
    
    
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
    
    
        if(pHead == NULL)
            return NULL;
        
        RandomListNode *p = NULL;
        p = pHead;
        while(p != NULL)
        {
    
    
            RandomListNode *tmp = new RandomListNode(p -> label);
            tmp -> next = p -> next;
            p -> next = tmp;
            p = tmp -> next;
        }
        
        p = pHead;
        while(p != NULL)
        {
    
    
            RandomListNode *tmp = p -> next;
            if(p -> random != NULL)
            {
    
    
                tmp -> random = p -> random -> next;
            }
            p = tmp -> next;
        }
        
        RandomListNode *pclone = NULL;
        p = pHead;
        pclone = pHead -> next;
        while(p -> next != NULL)
        {
    
    
            RandomListNode *tmp = p -> next;
            p -> next = tmp -> next;
            p = tmp;
        }
        
        return pclone;
    }
};

Guess you like

Origin blog.csdn.net/pikaqiu_n95/article/details/109708286