LeetCode之Copy List with Random Pointer

本文详细介绍了如何通过在原始链表每个节点后面插入相同值的节点并修改随机指针来实现链表的深度复制。通过两步操作:首先在每个节点后面插入同样值的节点;然后修改新插入节点的随机指针;最后将新旧链表分开,从而完成深度复制过程。此方法巧妙地解决了随机指针带来的复杂性。
/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
 /*
 本题题意是对链表进行深度复制,这里的难度主要是随机指针的问题。这里采用如下步骤求解该题:
 1.在原始链表每个节点的后面,插入与当前结点一样值的节点。
 2.修改每个插入结点的随机指针。
 3.分开新旧链表。
 参考自:https://github.com/soulmachine/leetcode
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        //1.在每个节点后面插入同样结点
        RandomListNode *cur(head);
        while(cur != nullptr){
            RandomListNode *tmp = new RandomListNode(cur->label);
            tmp->next = cur->next;
            cur->next = tmp;
            cur = cur->next->next;
        }
        
        //2.修改新插入结点的随机指针
        cur = head;
        while(cur != nullptr){
            if(cur->random != nullptr){
               cur->next->random = cur->random->next;             
            }
            cur = cur->next->next;
        }
        
        //3.拆开两个单链表
        cur = head;
        RandomListNode newHead(-1), *new_cur(&newHead);
        while(cur != nullptr){
            new_cur->next = cur->next;
            new_cur = new_cur->next;
            cur->next = cur->next->next;
            cur = cur->next;
        }
        return newHead.next;
    }
};

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值