大家好,我是蘇貝,本篇博客帶大家刷題,如果你覺得我寫的還不錯的話,可以給我一個贊👍嗎,感謝??
點擊查看題目
思路:
struct Node* copyRandomList(struct Node* head) {struct Node* cur=head;//1.copy原鏈表并將其插入到原鏈表中while(cur){struct Node* copy=(struct Node*)malloc(sizeof(struct Node));struct Node* next=cur->next;copy->val=cur->val;cur->next=copy;copy->next=next;cur=next;}//2.將copy->random指向cur->random的下一個節點cur=head;while(cur){struct Node* copy=cur->next;if(cur->random==NULL){copy->random=NULL;}else{copy->random=cur->random->next;}cur=cur->next->next;}//3.將copy的鏈表取下來cur=head;struct Node* newhead=NULL;struct Node* tail=NULL;while(cur){struct Node* copy=cur->next;struct Node* next=copy->next;if(tail==NULL){newhead=tail=copy;}else{tail->next=copy;tail=tail->next;}cur->next=next;cur=next;}if(tail)tail->next=NULL;return newhead;
}
好了,那么本篇博客就到此結束了,如果你覺得本篇博客對你有些幫助,可以給個大大的贊👍嗎,感謝看到這里,我們下篇博客見??