Leetcode 138. Copy List with Random Pointer

https://leetcode.com/problems/copy-list-with-random-pointer/description/
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.

deep copy vs shallow copy:
In a shallow copy, object B points to object A’s location in memory. In deep copy, all things in object A’s memory location get copied to object B’s memory location.

还有个lazy copy
什么时候需要这些?TODO

这个解法是看了leetcode上最高vote的解法,步骤就是:
1,创建并copy新的node(只copy label 和 next,random先不管),并把node insert到原节点的后面,l1原来list的节点。
2,copy新node的random。
l1->next->random = l1->random->next;
l1->next就是新的node,
l1->random是原来节点的random,(无论指向任何节点),这个random的next就是random的copy,正是新的l1->next->random想要指向的地方。这个非常smart。
3,最后就是break一个list to 两个list,
l1->next = l1->next->next; 是重建旧的list
l2->next = next;是新建新的list
最后的结果就是保证两个list没有任何连接。

/**
 * 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) {
        RandomListNode *l1 = head;
        RandomListNode *next = NULL;

        while(l1)
        {
            RandomListNode *node = new RandomListNode(l1->label);
            next = l1->next;
            l1->next = node;
            node->next = next;
            l1 = next;
        }
        
        l1 = head;
        while(l1)
        {
            if(l1->random != NULL)
            {
                l1->next->random = l1->random->next;
            }
            l1 = l1->next->next;
        }
        
        RandomListNode newhead(0);
        RandomListNode *l2 = & newhead;
        l1 = head;
        while(l1)
        {
            next = l1->next;
            l1->next = l1->next->next;
            l1 = l1->next;
            
            l2->next = next;
            l2 = l2->next;
        }
        
        return newhead.next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值