栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

复制带随机指针的链表( LeetCode 138 )

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

复制带随机指针的链表( LeetCode 138 )

题目链接

https://leetcode.cn/problems/copy-list-with-random-pointer/

问题分析

https://www.algomooc.com/708.html

代码实现 java

class Solution {
    public Node copyRandomList(Node head) {
        if(head==null)return null;
        Node cur=head;
        Map map=new HashMap<>();//哈希map用来存储已经创建的节点
        //第一次遍历
        while(cur!=null)
        {
            map.put(cur,new Node(cur.val));
            cur=cur.next;
        }
        //第二次遍历
        cur=head;
        while(cur!=null)
        {
            Node valcur=map.get(cur);
            Node valNextNode=map.get(cur.next);
            valcur.next=valNextNode;
            Node valRandomNode=map.get(cur.random);
            valcur.random=valRandomNode;
            cur=cur.next;
        }
        return map.get(head);
    }
}
c++

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head==NULL)return NULL;
        Node* cur=head;
        unordered_map map;

        while(cur!=NULL)
        {
            Node *valNode=new Node(cur->val);
            map[cur]=valNode;
            cur=cur->next;
        }

        cur=head;

        while(cur!=NULL)
        {
            Node* valcur=map[cur];
            Node* valNextNode=map[cur->next];
            valcur->next=valNextNode;
            Node* valRandomNode=map[cur->random];
            valcur->random=valRandomNode;
            cur=cur->next;
        }
        return map[head];
    }
};
python
"""
# Definition for a Node.
class Node:
    def __init__(self, x, next=None, random=None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        if head == None :
           return None
        cur=head

        map=dict()
        while cur!=None:
            new_node=Node(cur.val,None,None)
            map[cur]=new_node
            cur=cur.next

        cur=head
        while cur!=None:
            valcur=map.get(cur)
            valNextNode=map.get(cur.next)
            valcur.next=valNextNode
            valRandomNode=map.get(cur.random)
            valcur.random=valRandomNode
            cur=cur.next
        return map.get(head)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875943.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号