问题
思路
先说一个观点,在你实在不想看的时候,可以看了别人的方法,记住就行。总比什么都不想好。
但是,如果自己要是写的化,一定要自己想。
不见得能直接想出最好的方法,但是,必须得有思路,复杂的方法还是要把它实现了。其实这也是对编程能力最直观的体现,处理复杂逻辑的能力。
这个题目,正常的思路也很容易想。
总共两次遍历,第一次遍历复制链表Next指针域即可。
第二次遍历的时候,对于原来的链表,每一个节点的random记住它和头节点的偏移,然后在克隆链表里面,对于每一个节点的random让它从头节点走上面的offset即可。
代码
/*
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;
typedef RandomListNode Node;
Node* head = NULL;
Node* p = pHead;
Node* cur = NULL;
// just copy the list
while( p ){
Node* s = new Node(p->label);
if(!head){
head = s;
}else{
cur->next = s;
}
cur = s;
p = p->next;
}
// set the random pointer
p = pHead;
Node* q = head;
while(p){
// compute the offset
Node* prand = p->random;
int step = 0;
Node* tmp = pHead;
while(tmp != prand){
++step;
tmp = tmp->next;
}
// set the random pointer
Node* q_rand = head;
while(step--) q_rand = q_rand->next;
q->random = q_rand;
p = p->next;
q = q->next;
}
return head;
}
};