输入一个复杂链表(每一个节点中有节点值,以及两个指针,一个指向下一个节点,另外一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,不然判题程序会直接返回空)dom
也就是说这个链表,每一个节点除了指向下一个节点的指针,还额外带了一个指向任意节点的指针。指针
若是先复制出一份只含有next指针的链表,而后再进行额外指针的赋值,那么复杂度应该是O(n^2)blog
所以,先原位复制一份ABC链表,复制为AABBCCclass
而后,将复制的链表的额外指针,指向下一个节点。List
再拆分链表。引用
RandomListNode *Clone(RandomListNode *pHead) { // 提早返回 if (pHead == nullptr) { return nullptr; } RandomListNode *cur = pHead; // 复制,ABC变为AABBCC while (cur != nullptr) { RandomListNode *tmp_for_next = cur->next; // 这里能够不用拷贝 random cur->next = new RandomListNode(cur->label); cur->next->next = tmp_for_next; cur = tmp_for_next; } // 改变 random cur = pHead; while (cur != nullptr) { if (cur->random != nullptr) { cur->next->random = cur->random->next; } cur = cur->next->next; } // 拆分 RandomListNode* head_copy=pHead->next; RandomListNode *tmp; cur = pHead; while (cur->next != nullptr) { tmp = cur->next; cur->next = cur->next->next; cur = tmp; } return head_copy; }