- 利用随即指针不管怎么指,指的永远是该列表的特性,保存一个node地址和位置索引得map。然后肯定要建立对于得vector保存新的节点,这样就可以在后于如果这个node有随机指针的话,方便找到那个元素,然后指向它。
- 以及其中用的新节点再次赋值的技巧。
- node_vec.push_back(NULL);// 放入最后的结尾NULL节点(方便node_vec[i]->next = node_vec[i+1];处理)
/*
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) return NULL;
RandomListNode* new_head = pHead;
map<RandomListNode*,int> node_map;
vector<RandomListNode*> node_vec;
int i =0;//首先根据new_head 保存 新列表数组,且记录,地址以及对应得索引。(空节点没有push)
while(new_head){
node_vec.push_back(new RandomListNode(new_head->label));
node_map[new_head] = i;//不管怎么random也是指向的也是本列表的元素
new_head = new_head->next;
i++;
}
//进行链接
node_vec.push_back(NULL);// 放入最后的结尾NULL节点(方便node_vec[i]->next = node_vec[i+1];处理)
new_head = pHead;
i = 0;
while(new_head){
node_vec[i]->next = node_vec[i+1];
if(new_head->random){//并不是所有的node都有random指针
node_vec[i]->random = node_vec[node_map[new_head->random]];
}
new_head = new_head->next;
i++;
}
return node_vec[0];//返回新的头节点。
}
};