Problem: 138. 随机链表的复制
思路
- 插入拷贝节点在原链表的后面
目的: 找到原节点,就可以找到拷贝链表。 - 控制拷贝链表大的random。
copy->random = pcur->random->next;
- 拷贝节点下来,尾插拷贝链表,同时恢复原链表
复杂度
时间复杂度:
时间复杂度: O ( n ) O(n) O(n)
空间复杂度:
空间复杂度: O ( n ) O(n) O(n)
Code
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
typedef struct Node SLTNode;
struct Node* copyRandomList(struct Node* head) {
// 1.拷贝节点到原节点的后面
SLTNode* pcur = head;
while (pcur)
{
SLTNode* copy = (SLTNode*)malloc(sizeof(SLTNode));
copy->val = pcur->val;
//插入
SLTNode* next = pcur->next;
pcur->next = copy;
copy->next = next;
//迭代
pcur = next;
}
// 2.控制拷贝节点的random
pcur = head;
while (pcur)
{
SLTNode* copy = pcur->next;
SLTNode* next = copy->next;
if (pcur->random == NULL)
{
copy->random = NULL;
}
else
{
copy->random = pcur->random->next;
}
//迭代
pcur = next;
}
// 3. 把copy节点解下来,链接成新节点
pcur = head;
SLTNode* newhead = NULL,*newtail = NULL;
while (pcur)
{
SLTNode* copy = pcur->next;
SLTNode* next = copy->next;
if (newhead == NULL)
{
newhead = newtail = copy;
}
else
{
newtail->next = copy;
newtail = newtail->next;
}
//恢复原链表
pcur->next = next;
//迭代
pcur = next;
}
//返回拷贝好的新链表
return newhead;
}
运行结果测试: