标签:
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.
解题思路:简单的深拷贝思想,重点在于如何处理random结点,我用的是建立一个原本结点和新建结点的映射.
#include<iostream> #include<vector> #include<map> using namespace std; //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) {} }; RandomListNode *copyRandomList(RandomListNode *head) { RandomListNode* TmpHead = head; RandomListNode* ResultList = new RandomListNode(0); RandomListNode* TmpResultNode = ResultList; map<RandomListNode*, RandomListNode*>NodeMap; while (TmpHead!=NULL) { RandomListNode* p = new RandomListNode(TmpHead->label); NodeMap.insert(make_pair(TmpHead, p)); TmpResultNode->next = p; TmpResultNode = TmpResultNode->next; TmpHead = TmpHead->next; } TmpHead = head; TmpResultNode = ResultList->next; while (TmpHead!=NULL) { if (TmpHead->random != NULL) TmpResultNode->random = NodeMap[TmpHead->random]; TmpHead = TmpHead->next; TmpResultNode = TmpResultNode->next; } return ResultList->next; }
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/43527629