O(n) time O(1) Space C++


  • 22
    F
    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode * head) {
            RandomListNode * head_cp = nullptr, * cur = head, * cur_cp = nullptr;
            if (head == nullptr)
                return nullptr;
            while (cur != nullptr)
            {
                cur_cp = new RandomListNode (cur->label);
                cur_cp->next = cur->next;
                cur->next = cur_cp;
                cur = cur_cp->next;
            }
            cur = head;
            while (cur != nullptr)
            {
                cur_cp = cur->next;
                if (cur->random)
                    cur_cp->random = cur->random->next;
                cur = cur_cp ->next;
            }
            cur = head;
            head_cp = head->next;
            while (cur != nullptr)
            {
                cur_cp = cur->next;
                cur->next = cur_cp->next;
                cur = cur->next;
                if (cur)
                    cur_cp->next = cur->next;
            }
            return head_cp;
        }
    };

  • 0
    L

    wow, a great job!


  • 0
    P

    wow, this is genius


  • 0
    Y

    omg this is amazing


  • 0
    C

    I would appreciate it if you could explain your code for me.
    because I suppose that your code is better than others, I wanna learn your idea.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.