标签:方法 创建 and spl int struct com 链接 空间换时间
1 struct RandomListNode { 2 int label; 3 struct RandomListNode *next, *random; 4 RandomListNode(int x) : 5 label(x), next(NULL), random(NULL) { 6 } 7 };
1 /* 2 struct RandomListNode { 3 int label; 4 struct RandomListNode *next, *random; 5 RandomListNode(int x) : 6 label(x), next(NULL), random(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 RandomListNode* Clone(RandomListNode* pHead) 13 { 14 RandomListNode *res = new RandomListNode(0), *tmp = res, *pNode = pHead; //res是一个没有用的头结点。 15 map<RandomListNode*, RandomListNode*> mp; 16 while (pNode != NULL) { 17 RandomListNode *node = new RandomListNode(pNode->label); //创建新节点N‘(node) 18 tmp->next = node; 19 tmp = node; 20 mp[pNode] = node; //建立哈希映射<N, N‘> 21 pNode = pNode->next; 22 } 23 tmp = pHead; 24 for (map<RandomListNode*, RandomListNode*>::iterator it = mp.begin(); it != mp.end(); it++) { 25 //it->second: N‘, it->first: N, if->first->random: S, mp[S] = S‘ 26 it->second->random = mp[it->first->random]; 27 } 28 return res->next; 29 } 30 };
以空间换时间, O(n)的空间复杂度,O(n)的时间复杂度
解法三:
1 /* 2 struct RandomListNode { 3 int label; 4 struct RandomListNode *next, *random; 5 RandomListNode(int x) : 6 label(x), next(NULL), random(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 RandomListNode* Clone(RandomListNode* pHead) 13 { 14 if (pHead == NULL) 15 return NULL; 16 RandomListNode *pCurrent = pHead, *copyCurrent = NULL; 17 //复制一遍链表 18 while (pCurrent != NULL) { 19 RandomListNode* node = new RandomListNode(pCurrent->label); 20 node->next = pCurrent->next; 21 pCurrent->next = node; 22 pCurrent = node->next; 23 } 24 25 pCurrent = pHead; 26 while (pCurrent != NULL) { 27 copyCurrent = pCurrent->next; 28 if (pCurrent->random != NULL) 29 copyCurrent->random = pCurrent->random->next; 30 pCurrent = copyCurrent->next; 31 } 32 RandomListNode* pNode = pHead; 33 RandomListNode* pClonedHead = pNode->next; 34 RandomListNode* pClonedNode = pNode->next; 35 36 pNode->next = pClonedNode->next; 37 pNode = pClonedNode->next; 38 while (pNode != NULL) { 39 pClonedNode->next = pNode->next; 40 pClonedNode = pNode->next; 41 pNode->next = pClonedNode->next; 42 pNode = pClonedNode->next; 43 } 44 return pClonedHead; 45 } 46 };
标签:方法 创建 and spl int struct com 链接 空间换时间
原文地址:https://www.cnblogs.com/qinduanyinghua/p/11365542.html