35 questions to prove safety offer- face complex chain of copy - list

/ * 
Title: 
	implement a function, list replication complex, the head node returns the copy list. 
* / 
/ * 
Ideas: 
	The first step, a copy list S ', S is inserted in the original list. 
	The second step, chain S 'S replication of random pointer list. 
	The third step: S list split and S '. 
* / 

#Include <the iostream> 
#include <string.h> 
#include <algorithm> 
#include <the cmath> 
#include <stdio.h> 
#include <Vector> 
#include <Stack> 
#include <Queue> 

the using namespace STD; 

RandomListNode {struct 
    int label; 
    struct Next RandomListNode *, * Random; 
    RandomListNode (int X): 
            label (X), Next (NULL), Random (NULL) { 
    } 
}; 


RandomListNode * Clone (PHEAD RandomListNode *) 
{
    IF (PHEAD == nullptr a) PHEAD return; 
    // first step, a copy list S ', S is inserted in the original list. 
    = * • pNode PHEAD RandomListNode; 
    the while (• pNode) { 
        RandomListNode * = the newNode new new RandomListNode (pNode-> label); 
        newnode-> Next = pNode-> Next; 
        pNode-> Next the newNode =; 
        • pNode = pNode-> next-> Next ; 
    } 

    // second step, chain S 'S replication of random pointer list. 
    = PHEAD • pNode; 
    RandomListNode qNode * = pHead-> Next; 
    the while (qNode-> Next && qNode-> next-> Next) { 
        IF (! pNode-> Random = nullptr a) { 
            qNode-> Random = pNode-> random- > Next; 
        } 
        • pNode = qNode-> Next; 
        qNode = pNode-> Next;
    if(pNode->random != nullptr)
        qNode->random = pNode->random->next;

    //第三步:拆分链表S和S‘。
    pNode = pHead;
    qNode = pHead->next;
    RandomListNode* qHead = pHead->next;
    while(pNode){
        pNode->next = qNode->next;
        if(qNode->next != nullptr){
            qNode->next = qNode->next->next;
        }
        pNode = pNode->next;
        qNode = qNode->next;

    }

    return qHead;




}

int main(){
    RandomListNode* node1 = new RandomListNode(1);
    RandomListNode* node2 = new RandomListNode(2);
    RandomListNode* node3 = new RandomListNode(3);
    node1->next = node2;
    node2->next = node3;
    node2->random = node1;
    RandomListNode* res = Clone(node1);
    while(res){
        cout<<res->label<<endl;
        res = res->next;
    }

}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/11953965.html