题解 | #其实不难,难就难在不能用题目的链表节点直接赋值给新开辟的链表 复杂链表的复制#
复杂链表的复制
http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
RandomListNode* p1 = pHead;vector<int> values;
while(p1){
values.push_back(p1->label);
p1 = p1->next;
}
/*根据数组重建新的单链表*/
RandomListNode* head = new RandomListNode(NULL);
for(int i =values.size()-1;i>=0;--i){
RandomListNode* p2 = new RandomListNode(values[i]);
p2->next = head->next;
head->next = p2;
}
/*构建复杂链表*/
RandomListNode* p3 = head->next;RandomListNode* p4 = pHead;
while(p3){
if(p4->random){
RandomListNode* temp = head->next;
/*找出题目链表对应的random的节点 */
while(temp && temp->label != p4->random->label){
temp = temp->next;
}
/*此时temp 指向 新链表的random,赋值给p3就完了*/
p3->random = temp;
}
p3 = p3->next;
p4 = p4->next;
}
return head->next;
}
};