标签:turn 复杂链表的复制 dom节点 hash 程序 哈希 解法 ott solution
class Solution { public: RandomListNode *Clone(RandomListNode *pHead) { if (pHead == NULL) return NULL; RandomListNode *newHead = new RandomListNode(pHead->label); RandomListNode *curNode1 = pHead; RandomListNode *curNode2 = newHead; // 新旧链表形成Z链 while (curNode1) { curNode2->next = curNode1->next; curNode1->next = curNode2; curNode1 = curNode2->next; curNode2 = curNode1 == NULL ? NULL : new RandomListNode(curNode1->label); } curNode1 = pHead; curNode2 = newHead; // 新链添加random while (curNode1) { curNode2->random = curNode1->random == NULL ? NULL : curNode1->random->next; curNode1 = curNode2->next; curNode2 = curNode1 == NULL ? NULL : curNode1->next; } curNode1 = pHead; curNode2 = newHead; // 脱链 while (curNode1) { curNode1->next = curNode2->next; curNode2->next = curNode1->next == NULL ? NULL : curNode1->next->next; curNode1 = curNode1->next; curNode2 = curNode2->next; } return newHead; } };
解法二:利用哈希表
先构建新链表(label,next),同时哈希表存储(旧链表节点,新链表节点)映射关系
再遍历一遍旧链表,利用哈希的映射为新链表random赋值,oldNode->random = hash[newNode->random]
class Solution { public: RandomListNode *Clone(RandomListNode *pHead) { if (pHead == NULL) return NULL; map<RandomListNode *, RandomListNode *> m; RandomListNode *curNode1 = pHead; RandomListNode *curNode2 = new RandomListNode(curNode1->label); RandomListNode *newHead = curNode2; m[curNode1] = curNode2; while (curNode1) { curNode2->next = curNode1->next == NULL ? NULL : new RandomListNode(curNode1->next->label); curNode1 = curNode1->next; curNode2 = curNode2->next; m[curNode1] = curNode2; } curNode1 = pHead; curNode2 = newHead; while (curNode1) { curNode2->random = m[curNode1->random]; curNode1 = curNode1->next; curNode2 = curNode2->next; } return newHead; } };
标签:turn 复杂链表的复制 dom节点 hash 程序 哈希 解法 ott solution
原文地址:https://www.cnblogs.com/ruoh3kou/p/10075817.html