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.

Link:

[http://www.lintcode.com/en/problem/copy-list-with-random-pointer/]

解题思路:

解法1:O(n) space, DFS

使用哈希表储存已经克隆的节点,当在哈希表中找到节点的时候直接使用,否则就创新的节点。

解法2:O(1) space, O(n) time

将新的点储存在以前每个老的结点之后,如:
0->0'->1->1'->2->2'->NULL
最后再用一次循环拆开。
总共三个循环:
第一次将新的节点添加到老List中去,第二次循环将新节点的random指向对应的新节点,第三次讲List拆开,最后返回新的节点第一个(用dummy node记录)。

Tips:

在进行DFS的时候,umordered_map需要用引用传递,不然内存超出限制。并且要先于下一步dfs之前把节点添加到其中,不然时间超出限制。

完整代码:

DFS:
`
RandomListNode *copyRandomList(RandomListNode head)
{
unordered_map > um;
if(head == NULL)
return NULL;
return dfs(head, um);
}
RandomListNode *dfs(RandomListNode node,
unordered_map> &um)
{
if(node == NULL)
return NULL;
if(um.find(node->label) != um.end())
return um[node->label];
RandomListNode *temp = new RandomListNode(node->label);
um[temp->label] = temp;

    temp->random = dfs(node->random, um);
    
    temp->next = dfs(node->next, um);
    
    return temp;
}

O(1) Space:
RandomListNode *copyRandomList(RandomListNode *head)
{
if(head == NULL)
return NULL;
RandomListNode * dummy = new RandomListNode(0);
dummy->next = head;
//get nodes
while(head != NULL)
{
RandomListNode *temp = new RandomListNode(head->label);
temp->next = head->next;
head->next = temp;
head = head->next->next;
}
//get randoms point
head = dummy->next;
while(head != NULL)
{
if(head->random != NULL)
head->next->random = head->random->next;
head = head->next->next;
}
//complete list
dummy = dummy->next->next;
head = dummy;
while(head->next != NULL)
{
head->next = head->next->next;
head = head->next;
}
return dummy;
}
`

你可能感兴趣的:(Copy List with Random Pointer解题报告)