题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
关于复杂链表的数据结构描述:https://blog.nowcoder.net/n/954373f213e14eeab0a69ed0e9ef1b6e
解题思路:
1
、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
2
、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
3
、拆分链表,将链表拆分为原链表和复制后的链表
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead == nullptr)
return nullptr;
RandomListNode *cur = pHead;
//第一次遍历,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
while(cur){
RandomListNode * cloneNode = new RandomListNode(cur->label);
RandomListNode * next = cur->next;
cur->next = cloneNode;
cloneNode->next = next;
cur = next;
}
//第二次遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
cur = pHead;
while(cur){
cur->next->random = cur->random == nullptr ? nullptr : cur->random->next;
cur = cur->next->next;
}
//第三次遍历,拆分链表,将链表拆分为原链表和复制后的链表
cur = pHead;
RandomListNode *pclonehead = pHead->next;
while(cur){
RandomListNode * clone = cur->next;
cur->next = clone->next;
clone->next = clone->next == nullptr ? nullptr : clone->next->next;
cur = cur->next;
}
return pclonehead;
}
};