class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if (pHead == nullptr)
return pHead;
map<int,int> m;
RandomListNode* pNewHead = new RandomListNode(0);
if (pHead!= nullptr)
{
pNewHead->label = pHead->label;
m.insert({long(pHead), long(pNewHead)});
}
RandomListNode * pLast = pNewHead, *pHead1=pHead;
while (pHead->next != nullptr)
{
RandomListNode* pNewNode = new RandomListNode(pHead->next->label);
pLast->next = pNewNode;
pLast = pLast->next;
pHead = pHead->next;
m.insert({long(pHead), long(pLast)});
}
pLast->next =nullptr;
pLast=pNewHead;
pHead=pHead1;
while ( pLast->next != nullptr)
{
if (pHead->random == nullptr)
{
pLast->random = nullptr;
}
else
{
pLast ->random = (RandomListNode*)m[long(pHead->random)];
}
pLast = pLast->next;
pHead = pHead->next;
}
return pNewHead;
}
};
剑指offer--35题复杂链表的复制--C++实现--Hash表方法
最新推荐文章于 2024-08-20 19:32:04 发布