剑指offer之复杂链表的复制
复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&&tqId=11178&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
代码
/* struct RandomListNode { int label; struct RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) { } }; */ class Solution { public: RandomListNode* Clone(RandomListNode* pHead) { RandomListNode *head = pHead, *pHead2; if (head == NULL) { pHead2 = NULL; } else { while(head != NULL) { RandomListNode *p = new RandomListNode(head->label); p->next = head->next; head->next = p; head = head->next->next; } head = pHead; while(head != NULL) { if (head->random != NULL) { head->next->random = head->random->next; } head = head->next->next; } RandomListNode *p2 = NULL; head = pHead; pHead2 = head->next; p2 = pHead2; head->next = head->next->next; head = head->next; while(head != NULL) { p2->next = head->next; head->next = p2->next->next; p2 = p2->next; head = head->next; } } return pHead2; } };