Copy List with Random Pointer--LeetCode

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.


这是一道链表操作的题目,要求复制一个链表,不过链表的每个结点带有一个随机指针,指向某一个结点。
我们先介绍一种比较直接的算法,思路是先按照复制一个正常链表的方式复制,复制的时候把复制的结点做一个HashMap,以旧结点为key,新节点为value。这么做的目的是为了第二遍扫描的时候我们按照这个哈希表把结点的随机指针接上。这个算法是比较容易想到的,总共要进行两次扫描,所以时间复杂度是O(2*n)=O(n)。空间上需要一个哈希表来做结点的映射,所以空间复杂度也是O(n)。代码如下:

    public RandomListNode copyRandomList(RandomListNode head) {  
        if(head == null)  
            return head;  
        HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();  
        RandomListNode newHead = new RandomListNode(head.label);  
        map.put(head,newHead);  
        RandomListNode pre = newHead;  
        RandomListNode node = head.next;  
        while(node!=null)  
        {  
            RandomListNode newNode = new RandomListNode(node.label);  
            map.put(node,newNode);  
            pre.next = newNode;  
            pre = newNode;  
            node = node.next;  
        }  
        node = head;  
        RandomListNode copyNode = newHead;  
        while(node!=null)  
        {  
            copyNode.random = map.get(node.random);  
            copyNode = copyNode.next;  
            node = node.next;  
        }  
        return newHead;  
    }  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值