题目描述
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
思路分析
问题的关键在于random节点的拷贝,因为并不确定某个节点对应的random节点是否被创建。
解决思路
双指针
将拷贝后的每个节点插入到原始链表相应节点之后,这样连接random指针的时候,原始链表random指针后一个元素就是原始链表要找的随机节点,而该节点后一个就是它拷贝出来的新节点。(妙!)
if(cur->random == NULL)
clone->random = NULL;
else
clone->random = cur->random-.next;
在完成拷贝链表随机指针的链接后,根据奇偶序列连接新的链表,只需要每次越过相邻节点连接就可以。
/*
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* cur = pHead;
if(pHead == NULL) return NULL;
while(cur)
{
RandomListNode *clone = new RandomListNode(cur->label);
clone->next = cur->next;
cur->next = clone;
// cur = cur->next;
cur = clone->next;
}
cur = pHead;
RandomListNode* clone = pHead->next;
RandomListNode* res = pHead->next;
while(cur)
{
if(cur->random == NULL)
clone->random = NULL;
else
{
clone->random = cur->random->next;
}
cur = cur->next->next;
//check the end
if(clone->next != NULL)
{
clone = clone->next->next;
}
}
cur = pHead;
clone = pHead->next;
//seperation
while(cur)
{
cur->next = cur->next->next;
cur = cur->next;
if(clone->next != NULL)
{
clone->next = clone->next->next;
clone = clone->next;
}
}
return res;
}
};