题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
// 方法1
// step1: 建立链表
// step2: 完成random指针连接
// step3: 拆成两个链表
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
cloneNodes(pHead);
connectRandomNodes(pHead);
return reconnectNodes(pHead);
}
private:
void cloneNodes(RandomListNode* pHead) {
RandomListNode* pNode = pHead;
while (pNode) {
RandomListNode* pCloned = new RandomListNode(0);
pCloned->label = pNode->label;
pCloned->next = pNode->next;
pCloned->random = NULL;
pNode->next = pCloned;
pNode = pCloned->next;
}
}
void connectRandomNodes(RandomListNode* pHead) {
RandomListNode* pNode = pHead;
while (pNode) {
RandomListNode* pCloned = pNode->next;
if (pNode->random) {
pCloned->random = pNode->random->next;
}
pNode = pCloned->next;
}
}
RandomListNode* reconnectNodes(RandomListNode* pHead) {
RandomListNode* pNode = pHead;
RandomListNode* pClonedHead = NULL;
RandomListNode* pCloned = NULL;
if (pNode) {
pClonedHead = pNode->next;
pCloned = pNode->next;
pNode->next = pCloned->next;
pNode = pNode->next;
}
while (pNode) {
pCloned->next = pNode->next;
pCloned = pCloned->next;
pNode->next = pCloned->next;
pNode = pNode->next;
}
return pClonedHead;
}
};
// 方法2:利用map简化程序
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
cloneNodes(pHead);
return connectCloneNodes(pHead);
}
private:
unordered_map<RandomListNode*, RandomListNode*> um;
void cloneNodes(RandomListNode* pHead) {
RandomListNode* pNode = pHead;
while (pNode) {
RandomListNode* node = new RandomListNode(pNode->label);
node->next = NULL;
node->random = NULL;
um[pNode] = node;
pNode = pNode->next;
}
}
RandomListNode* connectCloneNodes(RandomListNode* pHead) {
RandomListNode* cloneHead = um[pHead];
while (pHead) {
um[pHead]->next = um[pHead->next];
um[pHead]->random = um[pHead->random];
pHead = pHead->next;
}
return cloneHead;
}
};