[LeetCode] 132: Copy List with Random Pointer
来源:互联网 发布:win7无法打开软件 编辑:程序博客网 时间:2024/06/05 16:17
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.
[Solution]
说明:版权所有,转载请注明出处。Coder007的博客/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// null node
if(NULL == head) return head;
// create new nodes of the old list
map<RandomListNode *, int> myMap;// stores the index of the nodes in the old list
vector<RandomListNode *> newNodes;// new nodes
RandomListNode *p = head;
int i = 0, j = 0;
while(p != NULL){
RandomListNode *node = new RandomListNode(p->label);
newNodes.push_back(node);
// stores index and increase index
myMap[p] = i++;
p = p->next;
}
// copy
p = head;
i = 0;
while(p != NULL){
if(p->next != NULL){
newNodes[i]->next = newNodes[i+1];
}
if(p->random != NULL){
newNodes[i]->random = newNodes[myMap[p->random]];
}
i++;
p = p->next;
}
return newNodes[0];
}
};
- [LeetCode] 132: Copy List with Random Pointer
- [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] 128: Valid Sudoku
- [LeetCode] 129: Validate Binary Search Tree
- [LeetCode] 130: Candy
- [LeetCode] 131: Clone Graph
- 优雅的点
- [LeetCode] 132: Copy List with Random Pointer
- Linux的有线网络 无线网络连接配置与解决方案
- [LeetCode] 133: Gas Station
- 使用dos编译java文件出现编码出错
- [LeetCode] 134: Wildcard Matching
- 1002. A+B for Polynomials (25)
- [LeetCode] 135: Word Break
- [LeetCode] 136: Word Break II
- [LeetCode] 137: Word Ladder