LintCode - Copy List with Random Pointer

时间:2023-03-10 07:12:09
LintCode - Copy List with Random Pointer

LintCode - Copy List with Random Pointer

Web Link

http://www.lintcode.com/en/problem/copy-list-with-random-pointer/

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.

- Challenge

Could you solve it with O(1) space?

Code - C++

/**
* 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 {
public:
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
void copyNext(RandomListNode* head) {
while (head != NULL) {
RandomListNode* newNode = new RandomListNode(head->label);
newNode->random = head->random;
newNode->next = head->next;
head->next = newNode;
head = head->next->next;
}
}
void copyRandom(RandomListNode* head) {
while (head != NULL) {
if (head->next->random != NULL) {
head->next->random = head->random->next;
}
head = head->next->next;
}
}
RandomListNode* splitList(RandomListNode* head) {
RandomListNode* newHead = head->next;
while (head != NULL) {
RandomListNode* temp = head->next;
head->next = temp->next;
head = head->next;
if (temp->next != NULL) {
temp->next = head->next;
}
}
return newHead;
}
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
if (head == NULL) {
return NULL;
}
copyNext(head);
copyRandom(head);
return splitList(head);
}
};

Tips:

  • None