首页 > 其他 > 详细

35. 复杂链表的复制

时间:2021-03-28 12:45:12      阅读:25      评论:0      收藏:0      [点我收藏+]
/*
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;

}
};

35. 复杂链表的复制

原文:https://www.cnblogs.com/N3ptuner/p/14587858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!