LeetCode题解——Copy List with Random Pointer
来源:互联网 发布:一生所爱 网络歌手 编辑:程序博客网 时间:2024/05/18 02:30
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.
Subscribe to see which companies asked this question
As an optimised solution, we could reduce the space complexity into constant. The idea is to associate the original node with its copy node in a single linked list. In this way, we don't need extra space to keep track of the new nodes.
The algorithm is composed of the follow three steps which are also 3 iteration rounds.
- Iterate the original list and duplicate each node. The duplicate of each node follows its original immediately.
- Iterate the new list and assign the random pointer for each duplicated node.
- Restore the original list and extract the duplicated nodes.
/** * 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) { RandomListNode *newHead, *l1, *l2; if (!head) return NULL; for (l1 = head; l1 != NULL; l1 = l1->next->next) { l2 = new RandomListNode(l1->label); l2->next = l1->next; l1->next = l2; } newHead = head->next; for (l1 = head; l1 != NULL; l1 = l1->next->next) { if (l1->random != NULL) l1->next->random = l1->random->next; } for (l1 = head; l1 != NULL; l1 = l1->next) { l2 = l1->next; l1->next = l2->next; if (l2->next != NULL) l2->next = l2->next->next; } return newHead;}};
0 0
- LeetCode题解——Copy List with Random Pointer
- LeetCode题解:Copy List with Random Pointer
- LeetCode - Copy List with Random Pointer 题解
- LeetCode: Copy List with Random Pointer题解
- leetcode - Copy List with Random Pointer题解
- LeetCode题解:Copy List with Random Pointer
- LeetCode 题解(88): Copy List with Random Pointer
- leetcode题解-138. Copy List with Random Pointer
- leetcode题解-138. Copy List with Random Pointer
- leetcode题解-138. Copy List with Random Pointer
- LeetCode——Copy List with Random Pointer
- leetcode 138 —— Copy List with Random Pointer
- LeetCode——138. Copy List with Random Pointer
- LeetCode — Copy List with Random Pointer 解题报告
- 【牛客网】copy-list-with-random-pointer题解
- LeetCode138—Copy List with Random Pointer
- [leetcode][list] Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- C/C++基本数据类型大小及表示范围
- Html+Css详解Css选择器,优先级与匹配原理
- 使用系统类NSURLSessionDownloadTask实现断点续传(音乐视频下载等)
- C++伴我每一天
- SUMO使用教程(五)
- LeetCode题解——Copy List with Random Pointer
- 第4讲 项目1-输出点阵图
- 简易QQ登录实现账号密码保存
- [NOIP 2011]铺地毯 模拟
- shell脚本操作mysql数据库-e参数执行各种sql
- 读取写入SharedPreferences数据
- opencv打开图片用到的ShowImage()函数和ResizeImage()函数
- RPC(Remote procedure call)
- SUMO使用教程(六)