struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
typedef pair<RandomListNode *, RandomListNode *> PAIR;
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) {
return nullptr;
}
cloneRandomList(&head);
PAIR pir = splitRandomList(head);
head = pir.first;
return pir.second;
}
void cloneRandomList(RandomListNode **head) {
RandomListNode *pNode = *head;
while (pNode != NULL) {
RandomListNode *tNode = new RandomListNode(pNode->label);
tNode->next = pNode->next;
pNode->next = tNode;
pNode = tNode->next;
}
makeRandomList(&(*head));
}
void makeRandomList(RandomListNode **head) {
RandomListNode *pNode = *head;
while (pNode != NULL) {
if (pNode->random != NULL) {
pNode->next->random = pNode->random->next;
}
pNode = pNode->next->next;
}
}
PAIR splitRandomList(RandomListNode *head) {
RandomListNode *newHead = head->next;
RandomListNode *headA, *headB;
headA = head;
headB = newHead;
while (head != NULL) {
head->next = newHead->next;
head = newHead->next;
if (head != NULL) {
newHead->next = head->next;
newHead = head->next;
}
}
return{ headA, headB };
}
};Copy List with Random Pointer
最新推荐文章于 2025-05-21 11:23:47 发布
本文介绍了一种复杂链表的复制方法,该链表节点除了包含next指针外还包含random指针。通过一种特殊的克隆过程,文章详细展示了如何在保持原有链表不变的情况下创建完全相同的副本。
1274

被折叠的 条评论
为什么被折叠?



