LeetCode题解——Copy List with Random Pointer

来源:互联网 发布:一生所爱 网络歌手 编辑:程序博客网 时间:2024/05/18 02:30

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.

Subscribe to see which companies asked this question

As an optimised solution, we could reduce the space complexity into constant. The idea is to associate the original node with its copy node in a single linked list. In this way, we don't need extra space to keep track of the new nodes.

The algorithm is composed of the follow three steps which are also 3 iteration rounds.

  1. Iterate the original list and duplicate each node. The duplicate of each node follows its original immediately.
  2. Iterate the new list and assign the random pointer for each duplicated node.
  3. Restore the original list and extract the duplicated nodes.
/** * 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 *newHead, *l1, *l2;    if (!head) return NULL;    for (l1 = head; l1 != NULL; l1 = l1->next->next) {        l2 = new RandomListNode(l1->label);        l2->next = l1->next;        l1->next = l2;    }    newHead = head->next;    for (l1 = head; l1 != NULL; l1 = l1->next->next) {        if (l1->random != NULL) l1->next->random = l1->random->next;    }    for (l1 = head; l1 != NULL; l1 = l1->next) {        l2 = l1->next;        l1->next = l2->next;        if (l2->next != NULL) l2->next = l2->next->next;    }    return newHead;}};



0 0