题解 | #复杂链表的复制#
复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
/** * struct RandomListNode { * int label; * struct RandomListNode *next; * struct RandomListNode *random; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead RandomListNode类 * @return RandomListNode类 */ struct RandomListNode* Clone(struct RandomListNode* pHead ) { // write code here struct RandomListNode* f(struct RandomListNode * pHead, struct RandomListNode * flag[]); struct RandomListNode* flag[1001] = {NULL}; return f(pHead, flag); } struct RandomListNode* f(struct RandomListNode* pHead, struct RandomListNode* flag[]) { if (flag[pHead->label] || !pHead) return NULL; // write code here struct RandomListNode* result = (struct RandomListNode*)malloc(sizeof( struct RandomListNode)); flag[pHead->label] = result; result->next = NULL; result->random = NULL; result->label = pHead->label; if (pHead->next) { result->next = f(pHead->next, flag); } if (pHead->random) { if (flag[pHead->random->label]) { result->random = flag[pHead->random->label]; } else { result->random = f(pHead->random, flag); } } return result; }