面试题35. 复杂链表的复制
请实现
copyRandomList
函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个next
指针指向下一个节点,还有一个random
指针指向链表中的任意节点或者null
。
思路:
1)原始1->2->3->N
2)复制成为 1->1->2->2
->3->3`->N
3)在将随机指针进行复制
4)将链表拆分成原链表和复制的链表
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head==NULL)
return NULL;
/*Node* org = head;
Node *copy = NULL;
while (org != NULL)
{
copy = org;
copy->next = org->next;
org->next = copy;
org = org->next->next;
}*/
//复制成 长链表
Node *org = head;
Node *pnext = NULL;
while (org != NULL)
{
pnext = org->next;
Node* tmp = new Node(org->val);
tmp->next = pnext;
org->next = tmp;
org = pnext;
}
// 复制随机指针
org = head;
Node *copy = head->next;
while (org != NULL)
{
//如果随即指针为空 需要判断
copy->random = org->random? org->random->next :NULL;
org = copy->next;
copy = org?org->next:org;
}
//拆分长链表
org = head;
copy = head->next;
Node *phead = copy;
while (org != NULL)
{
org->next = copy->next;
org = org->next;
// 最后一个结点 org为空 copu->next也为空
copy->next = org?org->next:org;
copy = copy->next;
}
return phead;
}
};
网友评论