LintCode - Copy List with Random Pointer
- LintCode - Copy List with Random Pointer
- Web Link
- Description
- Code - C
- Tips
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
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-05 20:29:59