假设有如下一个链表:
1
2
3
4
5
6
|
struct Node
{
int
value ;
struct Node *next ;
struct Node *random ;
}
|
1
|
Node *deepCopy (Node *head)
|
分两步
1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next
2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next, new1->next = new1->next->next
该算法时间复杂度O(N),空间复杂度O(1)
代码:
Node *deepCopy (Node *head)
{
Node* now = head;
Node* next = head->next;
while( now != NULL )
{
Node * copy = new Node;
copy->value = now->value;
copy->next = now->next;
now ->next = copy;
now = next;
next = next->next;
}
now = head;
while( now != NULL )
{
now->next->random = now->random->next;
now = now->next->next;
}
Node* head2 = head->next;
Node* newHead = head->next;
while( head2->next != NULL )
{
head->next = head2->next;
head2->next = head2->next->next;
head = head->next;
head2 = head2->next;
}
return newHead;
}
|