标签:style blog http io color os sp for on
这里是复制带有一个random指针的链表。是不是很熟悉啊。之前有做过克隆无向图的。那就借助leetcode Clone Graph的思路。
分两次遍历链表,一次先复制普通的含next的,另一次就是复制random了。利用map记录,可以一次就找到想要的点。
/** * 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) return head; RandomListNode *pre = new RandomListNode(0), *proc = head, *root = pre, *tmp_pre = pre; unordered_map<RandomListNode *, RandomListNode*> umap; while (proc) { root -> next = new RandomListNode(proc -> label); umap[proc] = root -> next; proc = proc -> next; root = root -> next; } while (head) { tmp_pre -> next -> random = umap[head -> random]; head = head -> next; tmp_pre = tmp_pre -> next; } return pre -> next; } };
leetcode[138] Copy List with Random Pointer
标签:style blog http io color os sp for on
原文地址:http://www.cnblogs.com/higerzhang/p/4159408.html