題目描述
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.
解題思路
- 先對原鏈表中的每個結點復制一個新的結點,并將復制的新結點的next和random域都和原結點的指向一樣;
- 再將原鏈表中的結點的next域都指向相應的新復制的結點;
- 然后調整復制的結點的random域的指向,指向相應的copy結點;
- 最后恢復原鏈表的連接情況,主要是next域的指向,由指向copy結點轉成指向原鏈表中相應的結點。
主要實現代碼
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head){
return NULL;
}
RandomListNode *currNode=head;
while(currNode){
RandomListNode *copyNode=new RandomListNode(currNode->label);
copyNode->next=currNode->next;
copyNode->random=currNode->random;
currNode->next=copyNode;
currNode=copyNode->next;
}
currNode=head;
while(currNode){//找到copy的結點的實際random結點
if(currNode->next->random){
currNode->next->random=currNode->random->next;
}
currNode=currNode->next->next;
}
RandomListNode *copyList=new RandomListNode(0);
copyList->next=head;
RandomListNode *pHead=copyList;
currNode=head;
while(currNode){
pHead->next=currNode->next;
pHead=currNode->next;
currNode->next=pHead->next;
currNode=pHead->next;
}
return copyList->next;
}
};