输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)。class Solution { public: void CloneList(RandomListNode* pHead){ RandomListNode* cur = pHead; RandomListNode* temp = NULL; while(cur != NULL){ temp = new RandomListNode(0); temp->label = cur->label; temp->next = cur->next; temp->random = NULL; cur->next = temp; cur = temp->next; } } void GetConnection(RandomListNode* pHead){ RandomListNode* cur = pHead; while(cur != NULL){ if(cur->random != NULL){ cur->next->random = cur->random->next; } cur = cur->next->next; } } RandomListNode* pickDump(RandomListNode* pHead) { if(pHead == NULL ) return NULL; RandomListNode* cur = pHead; RandomListNode* cloneHead; cloneHead = pHead->next; RandomListNode* pre = pHead; RandomListNode* clonepre=cloneHead; cur = cloneHead->next; while(cur != NULL){ pre->next = cur; clonepre->next = cur->next; pre = cur; clonepre=clonepre->next; cur = clonepre->next; } pre->next = NULL; clonepre->next =NULL; return cloneHead; } RandomListNode* Clone(RandomListNode* pHead) { if(pHead == NULL) return NULL; RandomListNode* cloneHead=NULL; CloneList(pHead); GetConnection(pHead); cloneHead = pickDump(pHead); return cloneHead; } };
我的问题在于链接的结尾没有结束,杂连在一起了。所以做题要注意细节,包括结尾!!!!!!!!!!!!!!!!!
时间: 2024-12-11 20:35:08