题目描述
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.
题目大意:给定一个链表,每个节点包含一个另外的随机的指针指向在链表中的随机一个结点或者为空。要求返回一个该链表的深拷贝。
解法1:主要思想还是先拷贝新节点,插入到原节点的后边;然后再 拷贝随机指针;最后将新节点从原链表中分离出,注意要保证原链表正常。
代码:Java
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null)
return head;
RandomListNode p,copy;
for(p = head;p!=null;p = p.next)
{
copy = new RandomListNode(p.label);
copy.next = p.next;
p = p.next = copy;
}
for (p = head;p!=null;p=copy.next)
{
copy = p.next;
copy.random = (p.random!=null?p.random.next:null);
}
p=head;
copy = p.next;
head = p.next;
for(;p!=null;)
{
p.next = copy.next;
p = p.next;
copy.next = (p!=null?p.next:null);
copy = copy.next;
}
return head;
}
}
为啥改为c++就跑的很快,很迷,上面代码内存都超了
解法2:使用哈希表
用Hash map来缩短查找时间,第一遍遍历生成所有新节点时同时建立一个原节点和新节点的哈希表,第二遍给随机指针赋值时,查找时间是常数级。
代码:c++
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head) return NULL;
RandomListNode *res = new RandomListNode(head->label);
RandomListNode *node = res;
RandomListNode *cur = head->next;
map<RandomListNode*, RandomListNode*> m;
m[head] = res;
while (cur) {
RandomListNode *tmp = new RandomListNode(cur->label);
node->next = tmp;
m[cur] = tmp;
node = node->next;
cur = cur->next;
}
node = res;
cur = head;
while (node) {
node->random = m[cur->random];
node = node->next;
cur = cur->next;
}
return res;
}
};