Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
copy-list-with-random-pointer.cpp 1.14 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-06-04 14:29 +08:00 . Update copy-list-with-random-pointer.cpp
// Time: O(n)
// Space: O(1)
/**
* 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:
RandomListNode *copyRandomList(RandomListNode *head) {
// Insert the copied node after the original one.
for (auto *curr = head; curr; curr = curr->next->next) {
auto *node = new RandomListNode(curr->label);
node->next = curr->next;
curr->next = node;
}
// Update random node.
for (auto *curr = head; curr; curr = curr->next->next) {
if (curr->random) {
curr->next->random = curr->random->next;
}
}
// Seperate the copied nodes from original ones.
RandomListNode dummy(0);
for (auto *curr = head, *copy_curr = &dummy;
curr;
copy_curr = copy_curr->next, curr = curr->next) {
copy_curr->next = curr->next;
curr->next = curr->next->next;
}
return dummy.next;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助