Title Description
Enter a complex linked list (each node has node values, and two pointers, one to the next node, and the other special pointer to any node), and the return result is the head of the copied complex linked list. (Note: please do not return the node reference in the parameter in the output result, otherwise the problem determination program will directly return null)
Train of thought: to be honest, I didn't understand what I was supposed to do in the first reading. In fact, the requirement here is to re open a linked list of space storage clones and return a header node. Therefore, pointer address assignment cannot be performed here. You can only reopen the space assignment and then link the relationship.
To do the problem, if we use next to open up a complete list of links, then when we link random nodes, we will go through a cycle to find and then randomly link nodes. But in this way, especially the link random nodes are very inefficient, and the time complexity will reach O (n^2), so we need to use an efficient method. The ideas are as follows:
We can copy the linked list first, and then copy it after the previous linked list, which is convenient for linking random nodes. It's directly the next of the random node of the previous node,
Finally, we can break it with even odd relationship.
class Solution { public: void FirstClone(RandomListNode* pHead)//Replication linked list { while(pHead != NULL) { RandomListNode * cloneNode = new RandomListNode(pHead->label); cloneNode->next = pHead->next; pHead->next = cloneNode; pHead = pHead->next->next; } } void SecondClone(RandomListNode* pHead)//Random chain { while(pHead != NULL) { if(pHead->random != NULL) { pHead->next->random = pHead->random->next; } pHead = pHead->next->next; } } RandomListNode* ThirdClone(RandomListNode* pHead)//Take apart the chain list. Here, take care to take it apart into two parts { RandomListNode* pNode = pHead; RandomListNode* ph = pHead->next,* pm = pHead->next; while(pm != NULL){ pNode->next = pm->next; pNode = pNode->next; if(pNode != NULL) { pm->next = pNode->next; } else pm->next = NULL; pm = pm->next; } return ph; } RandomListNode* Clone(RandomListNode* pHead) { if(pHead == NULL) return pHead; FirstClone(pHead); SecondClone(pHead); return ThirdClone(pHead); } };