代码实现
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
void CloneNodes(RandomListNode* pHead)
{
//RandomListNode *pNode = pHead;
RandomListNode *pNode;
pNode = pHead;
while(pNode != NULL)
{
RandomListNode* pClone = new RandomListNode(0);
pClone->label = pNode->label;
pClone->next = pNode->next;
pClone->random = NULL;
pNode->next = pClone;
pNode = pClone->next;
}
}
void ConnectSiblingNodes(RandomListNode* pHead)
{
RandomListNode* pNode = pHead;
while(pNode != NULL)
{
RandomListNode* pCloned = pNode->next;
if(pNode->random != NULL)
{
pCloned->random = pNode->random->next;
}
pNode = pCloned->next;
}
}
RandomListNode* ReconnectNodes(RandomListNode* pHead)
{
RandomListNode* pNode = pHead;
RandomListNode* pClonedHead = NULL;
RandomListNode* pClonedNode = NULL;
if(pNode != NULL) //初始化
{
pClonedHead = pClonedNode = pNode->next;
pNode->next = pClonedNode->next;
pNode = pNode->next;
}
while(pNode != NULL)
{
pClonedNode->next = pNode->next;
pClonedNode = pClonedNode->next;
pNode->next = pClonedNode->next;
pNode = pNode->next;
}
return pClonedHead;
}
RandomListNode* Clone(RandomListNode* pHead)
{
CloneNodes(pHead);
ConnectSiblingNodes(pHead);
return ReconnectNodes(pHead);
}
};
编程笔记
- 代码实现解题思路:1.复制原始链表的任意节点N并创建新节点N’,再把N’链接到N的后面;2.设置复制出来的节点的random,假设原始链表上的N的random指向节点S,那么其对应复制出来的N‘是N的next指向的节点,同样S’也是S的next指向的节点;3.将长链表拆分成两个链表,把奇数位置的节点用next链接起来就是原始链表,把偶数位置的节点用next链表链接起来就是复制出来的链表。
- 需要具备对困难问题的思维能力。本题中的复杂链表是 一种不太常见的数据结构,而且复制这种链表的过程也较为复杂,此题实现代码将复杂链表的复制过程分为三个部分。
- 需要具备分析时间效率和空间效率的能力。