//求救求救 请教一道剑指offer的题目:复杂链表的复制

//求救求救 请教一下大家
//为什么这个会返回wrong,cannot used original node of list
//我debug查看返回的地址是新建的不是原地址啊
//蟹蟹蟹蟹!!!

链接:https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba?f=discussion

class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        auto p = pHead;
        while(p)//原列表后插入复制的节点
        {
            auto newp = new RandomListNode(p->label);
            auto temp = p->next;
            p->next = newp;
            newp->next = temp;
            p = temp;
        }
        p = pHead;
        auto q = pHead->next;
        while(q)//拷贝random指针
        {
            if(p->random)
            q->random = p->random->next;
            p = p->next->next;
            if(q->next)
            q = q->next->next;
            else
            q = q->next;
        }
        q = pHead->next;
        auto temp = pHead;
        while(q)//整理出复制的节点
        {
            temp->next = q;
            temp = temp->next;
            if(q->next)
            q = q->next->next;
            else
            q = q->next;
        }
        return pHead->next;
     }
};

#学习路径#
全部评论
最后一个while循环 整理出复制的节点,有问题。 问题问的是需要深拷贝(即原来链表不变,并复制一个新的链表返回) 从最后一个while开始改 auto res = temp->next; while(q){ temp->next = q->next; if(q->next) q->next = q->next->next; q = q->next; temp=temp->next; } return res;
3
送花
回复 分享
发布于 2021-07-23 01:51

相关推荐

1 1 评论
分享
牛客网
牛客企业服务