RandomListNode *copyRandomList(RandomListNode *head) {
if(head == NULL) {
return NULL;
}
RandomListNode* curNode = head;
while(curNode != NULL) {
RandomListNode* curCopyNode = new RandomListNode(curNode->label);
RandomListNode* nextNode = curNode->next;
curNode->next = curCopyNode;
curCopyNode->next = nextNode;
curNode = nextNode;
}
curNode = head;
while(curNode != NULL) {
if(curNode->random != NULL) {
curNode->next->random = curNode->random->next;
}
curNode = curNode->next->next;
}
RandomListNode* copyListHead = head->next;
curNode = head;
while(curNode != NULL) {
RandomListNode* curCopyNode = curNode->next;
RandomListNode* nextNode = curCopyNode->next;
RandomListNode* nextCopyNode = NULL;
if(nextNode != NULL) {
nextCopyNode = nextNode->next;
}
curNode->next = nextNode;
curCopyNode->next = nextCopyNode;
curNode = nextNode;
}
return copyListHead;
}
[LeetCode] Copy List with Random Pointer
最新推荐文章于 2019-10-21 22:50:54 发布