leetcode - Copy List with Random Pointer
2013-10-13 19:31 张汉生 阅读(183) 评论(0) 编辑 收藏 举报
/** * 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) {} * }; */ /*struct NodeInfo{ RandomListNode * node; int pos; NodeInfo(RandomListNode * n, int p):node(n),pos(p){} }; bool compare(NodeInfo a, NodeInfo b){ return a.node - b.node < 0; } */ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { // Note: The Solution object is instantiated only once and is reused by each test case. //vector<NodeInfo> infos; map<unsigned, int> infoMap; vector<RandomListNode*> nodes; if (head== NULL) return head; int i=0; RandomListNode * temp = head; while (temp!=NULL){ infoMap[(unsigned)temp] = i; nodes.push_back(new RandomListNode(temp->label)); int sz = nodes.size(); if (sz>1) nodes[sz-2]->next = nodes[sz-1]; i++; temp = temp->next; } temp = head; i=0; while(temp!=NULL){ if(temp->random==NULL) nodes[i]->random=NULL; else{ nodes[i]->random = nodes[infoMap[(unsigned)temp->random]]; } i++; temp = temp->next; } return nodes[0]; } };