原文地址:https://www.jianshu.com/p/a0c983c292b1
时间限制:1秒 空间限制:32768K
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
我的代码
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead==nullptr)
return nullptr;
RandomListNode* pHead1=pHead;
RandomListNode* pHead2=new RandomListNode(pHead->label);
RandomListNode* cloneHead=pHead2;
map<RandomListNode*,RandomListNode*> m;
m[pHead1]=pHead2;
while(pHead1){
if(pHead1->next)
pHead2->next=new RandomListNode(pHead1->next->label);
else
pHead2->next=nullptr;
pHead1=pHead1->next;
pHead2=pHead2->next;
m[pHead1]=pHead2;
}
pHead1=pHead;pHead2=cloneHead;
while(pHead1){
pHead2->random=m[pHead1->random];
pHead1=pHead1->next;
pHead2=pHead2->next;
}
return cloneHead;
}
};
运行时间:3ms
占用内存:484k
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead==nullptr)
return nullptr;
RandomListNode* cur=pHead;
//复制
while(cur){
RandomListNode* node=new RandomListNode(cur->label);
node->next=cur->next;
cur->next=node;
cur=node->next;
}
cur=pHead;
while(cur){
RandomListNode* node=cur->next;
if(cur->random)
node->random=cur->random->next;
cur=node->next;
}
//拆分
RandomListNode* cloneHead=pHead->next;
cur=pHead;
while(cur->next){
RandomListNode* node=cur->next;
cur->next=cur->next->next;
cur=node;
}
return cloneHead;
}
};
运行时间:3ms
占用内存:484k