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.

这题貌似见过,大概是编程之美之类吧。

复习一下深拷贝和浅拷贝的区别:

深拷贝保存了指针指向的内容,二浅拷贝应对指针指示给指针赋值。

所以对于有指针的地方,浅拷贝非常不安全。

这段代码用了2个栈,感觉很不效率,空间O(n)。

有个空间O(1)的。

/**
 * 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) {
        stack<RandomListNode *> sk;
        stack<RandomListNode *> sk2;
        if(head == NULL)return NULL;
        RandomListNode *temp = head;
        RandomListNode *cp = new RandomListNode (0);
        RandomListNode *cpp = cp;
        while(temp != NULL)
        {
            int val = temp->label;
            RandomListNode* node = new RandomListNode(val);
            cpp->next = node;
            cpp = node;
            sk.push(temp);
        
            temp = temp ->next;
            sk.top()->next = cpp;
        }
        while(! sk.empty())
        {
            temp =sk.top();
            if(temp->random != NULL)
            temp->next->random = temp->random->next;
            sk2.push(temp);
            sk.pop();
        }
        while(! sk2.empty())
        {
            temp = sk2.top();
            sk2.pop();
            if(sk2.empty())temp->next =NULL;
            else
            {
                temp->next =sk2.top();
            }
        }
        return cp->next;
    }
};

  

原文地址:https://www.cnblogs.com/pengyu2003/p/3626836.html