Brushing notes (12)-complex linked list replication

Brushing notes (12)-complex linked list replication

Title description

Enter a complex linked list (each node has a node value, and two pointers, one points to the next node, and another special pointer points to any node), and the returned result is the head of the complex linked list after copying. (Note, please do not return the node reference in the parameter in the output result, otherwise the judgment program will directly return empty)

Idea: I didn't understand the meaning of the question at first, but only after reading the given structure.

First copy each node A->. A *, and insert the copied node A * between A and B.

The linked list is: A, A *, B, B *, C, C * ...

Modify the next pointer and random pointer, the next pointer of A * points to the next pointer of next;

Split and modify the next pointer

/*
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) return NULL;
        RandomListNode* p=pHead;
        while(p!=NULL)
        {
            RandomListNode *node = new RandomListNode(p->label);
            node->next=p->next;
            p->next=node;
            p=node->next;
        }
        p=pHead;
        while(p!=NULL)
        {
            RandomListNode *node = p->next;
            if(p->random){               
                node->random = p->random->next;
            }
            p = node->next;
            /*if(p->random->next!=NULL)
                p->next->random=p->random->next;
            p=p->next->next;*/
        }
        p=pHead;
        RandomListNode* q=p->next;
        RandomListNode *tmp;
        while(p->next!=NULL)
        {
            tmp = p->next;
            p->next =tmp->next;
            p = tmp;
        }
        return q;
    }
};

 

Published 36 original articles · 19 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/GJ_007/article/details/105466177