题目描述
复制复杂链表。每个节点除了next,还有一个指向链表中任意节点或者nullptr的指针。
struct ComplexListNode { int m_nValue; ComplexListNode *m_pNext; ComplexListNode * m_pSibling; }
思路一:
- 复制链表上每个节点,并用next链接起来
- 设置每个节点m_pSibling
思路二:
时间耗费在第二步,直接设置一个哈希表,用空间换时间
思路三:
- 在每个节点后面链接自己的复制节点
- pnode->random = pnode->next->random
- 断开链接
leetcode
- 复制带随机指针的链表
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深拷贝。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* copy=head;
while(copy!=nullptr)
{
Node *pcloned = new Node();
pcloned->val = copy->val;
pcloned->next = copy->next;
pcloned->random = nullptr;
copy->next = pcloned;
copy=pcloned->next;
}
copy = head;
while(copy!=nullptr)
{
Node *pcloned = copy->next;
if(copy->random != nullptr)
{
pcloned->random = copy->random -> next;
}
copy = pcloned->next;
}
copy = head;
Node *cloneHead = nullptr;
Node *cloneNode = nullptr;
if(copy!=nullptr)
{
cloneHead = copy->next;
cloneNode = copy->next;
copy->next = cloneHead->next;
copy = copy->next;
}
while(copy!=nullptr)
{
cloneNode ->next = copy->next;
cloneNode = cloneNode->next;
copy->next = cloneNode->next;
copy=copy->next;
}
return cloneHead;
}
};