1. 程式人生 > >Leetcode 138. Copy List with Random Pointer

Leetcode 138. Copy List with Random Pointer

cto 存儲空間 行操作 return 映射 air and pre int

/**
 * 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) {
        std::map
<RandomListNode *, int> node_map; std::vector<RandomListNode *> node_vec; RandomListNode * ptr = head; int i=0; while(ptr) { node_vec.push_back(new RandomListNode(ptr->label)); node_map.insert(make_pair(ptr, i)); ptr
= ptr->next; ++i; } node_vec.push_back(0); ptr = head; i = 0; while(ptr) { node_vec[i]->next = node_vec[i+1]; if(ptr->random) { int id = node_map[ptr->random]; node_vec[i]
->random = node_vec[id]; } ptr = ptr->next; i++; } return node_vec[0]; } };

這個是借助了映射的概念,用了額外的存儲空間,其實可以不用額外的存儲空間,將新節點增添到對應節點的後面,這樣統一進行操作就方便了。

Leetcode 138. Copy List with Random Pointer