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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43476349/article/details/83993427