LeetCode: 138. Copy List with Random Pointer
Title Description
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Solving problems
- Copy each node of the original list as its next node (copy Random List Without Random).
- Copy the random node of the node, even the next node of the random node of the original node (copy Random List Random).
- Generate a replicated list and restore the original list (copy Random List Generator).
- Example (1 (3) = > 2 (1) = > 3 (nullptr) = > 4 (1) = > nullptr)
a. Initial state
b. Replication list (excluding random) with replication node as the next node of the original node
c. random attributes of replicated linked lists
Processing a node:
Processing all nodes:
d. Generate duplicate linked list and restore original linked list.
Processing a node:
Processing two nodes:
Processing three nodes:
Processing all nodes:
AC code
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution
{
private:
// Copy Random List (excluding random attributes) and insert the copy content after the original node
void copyRandomListWithoutRandom(RandomListNode *head)
{
if(head == nullptr) return ;
auto iter = head;
// Copy head node
RandomListNode * headCopy = new RandomListNode(head->label);
// Insert headCopy behind the head
headCopy->next = head->next;
head->next = headCopy;
// Processed nodes
copyRandomListWithoutRandom(head->next->next);
}
// Copy random attributes
void copyRandomListRandom(RandomListNode *head)
{
if(head == nullptr) return;
// NOTE: The next pointer to the original node points to the copied node
if(head->random != nullptr)
{
head->next->random = head->random->next;
}
// Processed nodes
copyRandomListRandom(head->next->next);
}
// Generate a copy list and restore the original list
RandomListNode* copyRandomListGenerator(RandomListNode *head)
{
if(head == nullptr) return nullptr;
// NOTE: The next pointer to the original node points to the copied node
RandomListNode* headCopy = head->next;
head->next = headCopy->next;
// Continue to process the following nodes
headCopy->next = copyRandomListGenerator(head->next);
return headCopy;
}
public:
RandomListNode *copyRandomList(RandomListNode *head)
{
// Copy Random List (excluding random attributes) and insert the copy content after the original node
copyRandomListWithoutRandom(head);
// Copy random attributes
copyRandomListRandom(head);
// Generate a copy list and restore the original list
return copyRandomListGenerator(head);
}
};