LeetCode: Copy List with Random Pointer

本文介绍了一种高效算法,用于深拷贝含有额外随机指针的链表。该算法首先将原链表节点与其拷贝节点交织在一起,然后通过O(1)时间复杂度设置随机指针,最后分离两链表。此方法巧妙地解决了随机指针的拷贝问题。

Copy List with Random Pointer


A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

耗时:104ms。


算法步骤:

  1.  将现有List复制一份到原有List, 即形成 A -> A' -> B -> B' -> .......的形式。 这样可以方便处理random节点的情况,假设A指向X, 如果分别创建两个链表,则需要O(N)的时间复杂度使得A' 指向 X'。但是如果建立上述结构,则可以在O(1)的时间内完成。即为:A->next->random = X->next;
  2. 将链表 A -> A' -> B -> B' -> .......断开,形成两条链表 A->B->... 和A'->B'->....

代码实现:
/**
 * 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) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        
        if(head == NULL)//exception
            return NULL;
        
        //copy all next node in the list   
        RandomListNode* t = head;
        while(t != NULL)
        {
            RandomListNode* tnext = t->next;
            RandomListNode* newt = new RandomListNode(t->label);
            t->next = newt;
            newt->next = tnext;
            t = tnext;
        }
        
        //copy all random node in the list 
        t = head;
        while(t!=NULL)
        {
            if(t->random != NULL)
            {
                t->next->random = t->random->next;   
            }
            t = t->next;
            t = t->next;
        }
        
        
        //spilt the list to result.
        RandomListNode* copyHead = head->next;;
        RandomListNode* copyt = copyHead;
        t = head;
        
        while(t!=NULL)
        {
            //delete t->next;
            t->next = t->next->next;
            if(copyt->next != NULL)
                 copyt->next = copyt->next->next;
            
            t = t->next;
            copyt = copyt->next;
        }
        
        return copyHead;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值