第一种方式:
/*// Definition for a Node.class Node {public:int val;Node* next;Node* random;Node(int _val) {val = _val;next = NULL;random = NULL;}};*/class Solution {public:Node* copyRandomList(Node* head) {//在原有的链表的每一个节点后面都插入一个节点Node* pt = head;while(pt){Node* pNew = new Node(pt->val);pNew->next = pt->next;pt->next = pNew;pt= pt->next->next;}//把新插入的节点的random进行赋值pt = head;while(pt){if(pt->random){pt->next->random = pt->random->next;}pt = pt->next->next;}//把新链表抠出来pt = head;Node* dummy = new Node(-1);Node* newpt = dummy;while(pt){newpt->next = pt->next;newpt = newpt->next;pt->next = newpt->next;pt = pt->next;}newpt->next = nullptr;return dummy->next;}};
第二种,借助map,存的是新旧链表的node对
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
map<Node*, Node*> mp;
Node* pt = head;
while(pt)
{
mp[pt] = new Node(pt->val);
pt = pt->next;
}
pt = head;
while(pt)
{
mp[pt]->next = mp[pt->next];
if(pt->random)
{
mp[pt]->random = mp[pt->random];
}
pt = pt->next;
}
return mp[head];
}
};
第三种,借助map,存的是旧链表的节点的idx
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
map<Node*, int> mp;
vector<Node*> v;
Node* pt = head;
while(pt)
{
Node* newnode = new Node(pt->val);
v.push_back(newnode);
mp[pt] = v.size() - 1;
pt = pt->next;
}
Node* dummy = new Node(-1);
Node* newpt = dummy;
pt = head;
for(int i = 0; i < v.size(); i++)
{
newpt->next = v[i];
newpt = newpt->next;
if(pt->random)
newpt->random = v[mp[pt->random]];
pt = pt->next;
}
// newpt->next = nullptr;
return dummy->next;
}
};
