LeetCode: Copy List with Random Pointer
来源:互联网 发布:网络电影播放器 编辑:程序博客网 时间:2024/06/08 12:28
Copy List with Random Pointer
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.
耗时:104ms。算法步骤:
- 将现有List复制一份到原有List, 即形成 A -> A' -> B -> B' -> .......的形式。 这样可以方便处理random节点的情况,假设A指向X, 如果分别创建两个链表,则需要O(N)的时间复杂度使得A' 指向 X'。但是如果建立上述结构,则可以在O(1)的时间内完成。即为:A->next->random = X->next;
- 将链表 A -> A' -> B -> B' -> .......断开,形成两条链表 A->B->... 和A'->B'->....
代码实现:
/** * 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) { if(head == NULL)//exception return NULL; //copy all next node in the list RandomListNode* t = head; while(t != NULL) { RandomListNode* tnext = t->next; RandomListNode* newt = new RandomListNode(t->label); t->next = newt; newt->next = tnext; t = tnext; } //copy all random node in the list t = head; while(t!=NULL) { if(t->random != NULL) { t->next->random = t->random->next; } t = t->next; t = t->next; } //spilt the list to result. RandomListNode* copyHead = head->next;; RandomListNode* copyt = copyHead; t = head; while(t!=NULL) { //delete t->next; t->next = t->next->next; if(copyt->next != NULL) copyt->next = copyt->next->next; t = t->next; copyt = copyt->next; } return copyHead; }};
0 0
- [leetcode][list] 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 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: Copy List with Random Pointer
- LeetCode | Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- LeetCode OJ:Copy List with Random Pointer
- LeetCode(138)Copy List with Random Pointer
- [LeetCode] - Copy List with Random Pointer
- 矩阵树定理
- HDOJ Choose the best route 2680【最短路Dijkstra+反向建图】
- 学生信息管理系统总结
- 编译器错误error: expected unqualified-id before 'using'| ||=== Build finished: 1
- hdu 2222 AC自动机入门详解
- LeetCode: Copy List with Random Pointer
- hdu 5383 Yu-Gi-Oh!(最大费用费用流)
- Java,spring程序中实时获取.properties属性key的value
- HDU 2563 统计问题 (DFS + 打表)
- 结构之美——优先队列三大结构(三)——Pairing Heap
- Visual studio 2013 批量删除空行的方式
- 黑马程序员———C语言———【枚举、typedef、宏、static和extern、文件操作】
- input文本框没有onchange事件,可以通过下面两种方法实现当input内容改变时触发事件
- Codeforces Round #316 (Div. 2) C. Replacement