面试题35. 复杂链表的复制 哈希表/思维

181 篇文章 0 订阅
32 篇文章 1 订阅

https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
在这里插入图片描述

思路一:借助哈希表,建立新旧节点之间的映射即可。

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head==NULL)
            return NULL;
        unordered_map<Node*,Node*> m;
        Node *cur=head,*n;
        while(cur!=NULL)
        {
            n=new Node(cur->val);
            m[cur]=n;
            cur=cur->next;
        }
        cur=head;
        while(cur!=NULL)
        {
            n=m[cur];
            n->next=m[cur->next];
            if(cur->random!=NULL)
                n->random=m[cur->random];
            cur=cur->next;
        }
        return m[head];
    }
};

思路二:不花费额外的空间。首先在每个节点后面挂一个新的节点(复制),然后再次遍历链表,这时候的 r a n d o m random random就比较好处理了。

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head==NULL)
            return NULL;
        Node *n,*cur=head,*nxt;
        while(cur!=NULL)
        {
            n=new Node(cur->val);
            nxt=cur->next;
            n->next=nxt;
            cur->next=n;
            cur=nxt;
        }
        cur=head;
        while(cur!=NULL)
        {
            nxt=cur->next;
            nxt->random=cur->random;
            if(nxt->random!=NULL)
                nxt->random=nxt->random->next;
            cur=cur->next;
            if(cur!=NULL)
                cur=cur->next;
        }
        Node *ans=head->next;
        cur=head,nxt=cur->next;
        while(cur!=NULL)
        {
            nxt=cur->next;
            cur->next=nxt->next;
            cur=cur->next;
            if(cur!=NULL)
                nxt->next=cur->next;
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值