复杂链表的复制

复杂链表的复制

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tPage=2

参考:https://www.nowcoder.com/profile/4741081/codeBookDetail?submissionId=17079420

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead==NULL)
        {
            return NULL;
        }
        //定义一个哈希表
        unordered_multimap<RandomListNode*,RandomListNode*> table;
        //开辟一个头结点
        RandomListNode* pClonedHead = new RandomListNode(pHead->label);
        pClonedHead->next = NULL;
        pClonedHead->random = NULL;

        //将头结点放入map中
        table.insert(make_pair(pHead,pClonedHead));

        //设置操作指针
        RandomListNode* pNode = pHead->next;
        RandomListNode* pClonedNode = pClonedHead;
        //第一遍先将简单链表复制下
        while(pNode!=NULL)
        {
            //不断开辟pNode的拷贝节点
            RandomListNode* pClonedTail = new RandomListNode(pNode->label);
            pClonedTail->next = NULL;
            pClonedTail->random = NULL;

            //连接新结点,更新当前结点
            pClonedNode->next = pClonedTail;
            pClonedNode = pClonedTail;
            //将对应关系插入到哈希表中
            table.insert(make_pair(pNode,pClonedTail));
            //向后移动操作结点
            pNode = pNode->next;
        }
        //需从头设置random结点,设置操作指针
        pNode = pHead;
        pClonedNode = pClonedHead;
        while(pNode!=NULL)
        {
            if(pNode->random!=NULL)
            {
                pClonedNode->random = table.find(pNode->random)->second;
            }

            pNode = pNode->next;
            pClonedNode = pClonedNode->next;
        }
        return pClonedHead;
    }
};
全部评论

相关推荐

拉丁是我干掉的:把上海理工大学改成北京理工大学。成功率增加200%
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务