138. 复制带随机指针的链表

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(!head)   return NULL;
        for(auto p=head;p;p=p->next->next)//复制小弟
        {
            auto t=new Node(p->val);
            t->next=p->next;
            p->next=t;
        }
        for(auto p=head;p;p=p->next->next)//复制random
            if(p->random)
                p->next->random=p->random->next;
        //抽出链表
        auto dummy=new Node(-1),tail=dummy;
        for(auto p=head;p;p=p->next)
        {
            //将小弟节点插入新链表
            auto new_node=p->next;
            tail=tail->next=new_node;
            //将原链表恢复
            p->next=p->next->next;
        }
        return dummy->next;
    }
};
posted @   穿过雾的阴霾  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示