题解 | #复杂链表的复制#

复杂链表的复制

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;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务