Copy List with Random Pointer
https://leetcode.com/problems/copy-list-with-random-pointer/description/
Thoughts
Code
/*
* @lc app=leetcode id=138 lang=cpp
*
* [138] Copy List with Random Pointer
*/
// @lc code=start
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if (head == nullptr) return nullptr;
auto cur = head;
while (cur != nullptr) {
auto node = new Node(cur->val, cur->next, nullptr);
cur->next = node;
cur = node->next;
}
cur = head;
while (cur != nullptr) {
auto node = cur->next;
if (cur->random != nullptr) node->random = cur->random->next;
cur = node->next;
}
auto new_head = head->next, new_cur = new_head;
cur = head;
while (cur != nullptr) {
cur->next = new_cur->next;
cur = cur->next;
if (cur != nullptr) {
new_cur->next = cur->next;
new_cur = new_cur->next;
}
}
return new_head;
}
};
// @lc code=end
Analysis
Last updated