LeetCode-138-Copy List with Random Pointer
阿新 • • 發佈:2019-02-06
nod addition pan con code class div poi add
算法描述:
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