Copy List with Random Pointer
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.
耗时:104ms。算法步骤:
- 将现有List复制一份到原有List, 即形成 A -> A' -> B -> B' -> .......的形式。 这样可以方便处理random节点的情况,假设A指向X, 如果分别创建两个链表,则需要O(N)的时间复杂度使得A' 指向 X'。但是如果建立上述结构,则可以在O(1)的时间内完成。即为:A->next->random = X->next;
- 将链表 A -> A' -> B -> B' -> .......断开,形成两条链表 A->B->... 和A'->B'->....
代码实现:
/**
* 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 == NULL)//exception
return NULL;
//copy all next node in the list
RandomListNode* t = head;
while(t != NULL)
{
RandomListNode* tnext = t->next;
RandomListNode* newt = new RandomListNode(t->label);
t->next = newt;
newt->next = tnext;
t = tnext;
}
//copy all random node in the list
t = head;
while(t!=NULL)
{
if(t->random != NULL)
{
t->next->random = t->random->next;
}
t = t->next;
t = t->next;
}
//spilt the list to result.
RandomListNode* copyHead = head->next;;
RandomListNode* copyt = copyHead;
t = head;
while(t!=NULL)
{
//delete t->next;
t->next = t->next->next;
if(copyt->next != NULL)
copyt->next = copyt->next->next;
t = t->next;
copyt = copyt->next;
}
return copyHead;
}
};
本文介绍了一种高效算法,用于深拷贝含有额外随机指针的链表。该算法首先将原链表节点与其拷贝节点交织在一起,然后通过O(1)时间复杂度设置随机指针,最后分离两链表。此方法巧妙地解决了随机指针的拷贝问题。
461

被折叠的 条评论
为什么被折叠?



