35. 复杂链表的复制

/*
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 == nullptr) return nullptr;
    auto it = pHead;
    //复制一份
    while(it){
        RandomListNode* newnode = new RandomListNode(it->label);
        newnode->next = it->next;
        it->next = newnode;
        it = newnode->next;
    }
    //设置random
    it = pHead;
    while(it){
        if(it->random == nullptr){
            it->next->random = it->random;
        }else{
            it->next->random = it->random->next;
        }
        it = it->next->next;
    }
    auto source = pHead;
    auto copy = pHead->next;
    auto ans = copy;
    while(source){
        auto next = source->next;
        if(next != nullptr){
            source->next = source->next->next;
        }else{
            
        }
        source = next;
    }


    return copy;

}
};
posted @ 2021-03-28 09:56  rxh1999  阅读(27)  评论(0编辑  收藏  举报