LeetCode-138-Copy List with Random Pointer
Posted 无名路人甲
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-138-Copy List with Random Pointer相关的知识,希望对你有一定的参考价值。
算法描述:
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.
解题思路:分三步走,1 在每个节点后面复制该节点;2 复制随机指针 cur->next->random = cur->random->next; 3将两个链表分离。
RandomListNode *copyRandomList(RandomListNode *head) { if(head == nullptr) return head; RandomListNode* cur = head; while(cur!=nullptr){ RandomListNode* temp = new RandomListNode(cur->label); temp->next = cur->next; cur->next = temp; cur = cur->next->next; } RandomListNode* newHead = head->next; cur = head; while(cur!=nullptr){ if(cur->random!=nullptr) cur->next->random = cur->random->next; cur = cur->next->next; } cur = head; RandomListNode* ncur = newHead; while(cur!=nullptr){ cur->next = ncur->next; cur = cur->next; if(cur!=nullptr){ ncur->next = cur->next; ncur= ncur->next; } } return newHead; }
以上是关于LeetCode-138-Copy List with Random Pointer的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 138. Copy List with random pointer
LeetCode-138-Copy List with Random Pointer
Leetcode 138. Copy List with Random Pointer
LeetCode 138. Copy List with Random Pointer