复杂链表的复制

来源:互联网 发布:手机看电视台直播软件 编辑:程序博客网 时间:2024/06/06 06:55


/*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 pHead;cloneNext(pHead);        cloneRandom(pHead);        pHead = separate(pHead);        return pHead;}private:    void cloneNext(RandomListNode* head){       while(head != NULL){            RandomListNode* temp = new RandomListNode(head->label);            temp->next = head->next;            head->next = temp;            head = temp->next;        }    }    void cloneRandom(RandomListNode* head){        while(head != NULL){            if(head->random != NULL)                head->next->random = head->random->next;            head = head->next->next;        }    }    RandomListNode* separate(RandomListNode* head){        RandomListNode* temp = head->next;        RandomListNode* newHead = head->next;        while(newHead->next != NULL){            head->next = newHead->next;           newHead->next = newHead->next->next;            head = head->next;            newHead = newHead->next;        }        head->next = NULL;        return temp;    }};


0 0