[LeetCode]138. Copy List with Random Pointer

来源:互联网 发布:域名 知识产权 编辑:程序博客网 时间:2024/06/06 19:33

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.

——————————————————————————————————————————————————————————————————————————

Solution:

第一种方法:可以使用哈希表记录原节点和新节点一一对应的关系,以此找到random指向的节点。两次迭代。

时间复杂度:O(2n)=O(n)

空间复杂度:O(n)

/** * 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) {        if (!head)            return head;                map<RandomListNode*, RandomListNode*> relationship;        RandomListNode *pre = new RandomListNode(-1);        RandomListNode *cur = pre;                RandomListNode *ptr = head;                while (head) {            cur->next = new RandomListNode(head->label);            /*            不能在此new random节点,因为是指向list内部的节点,而不是新节点            if (head->random)                cur->next->random = new RandomListNode(head->random->label);            */            if (head->next)                cur->next->next = new RandomListNode(head->next->label);                        relationship[head] = cur->next;                        cur = cur->next;            head = head->next;        }                head = ptr;        cur = pre->next;        while (head) {            if (head->random)                cur->random = relationship[head->random];                        head = head->next;            cur = cur->next;        }                        return pre->next;    }};


第二种方法:三次迭代。第一次将每个新节点建立在每个旧节点后面;第二次将每个新节点的random指针指向旧节点random指针指向的下一个节点;第三次提取出新节点;

时间复杂度:O(3n)=O(n)

空间复杂度:O(1)