【LeetCode】【138】【Copy List with Random Pointer】【链表】

题目: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.
解题思路:复杂链表的复制问题,每一个节点都有两个指针,一个指向下一个节点,一个指向随机的节点。思路是先按照指向下一节点的顺序复制出一个简单链表,再用hash表的方法快速找到每个节点指向的随机节点。
代码:

class RandomListNode {
      int label;
      RandomListNode next, random;
      RandomListNode(int x) { this.label = x; }
  };
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null) return null;
        HashMap<RandomListNode,RandomListNode> map = new HashMap<>();  //这个hash表用来快速找到指向的随机节点
        RandomListNode ans = new RandomListNode(head.label);
        map.put(head,ans);
        //复制单链表
        RandomListNode node = ans;
        RandomListNode curr = head;
        curr = curr.next;
        while (curr != null){
            RandomListNode temp = new RandomListNode(curr.label);
            node.next = temp;
            node = node.next;
            map.put(curr,temp);
            curr = curr.next;
        }
        //复制随机节点
        node = ans;
        while (head!=null){
            if(head.random == null)node.random = null;
            else node.random = map.get(head.random);
            head = head.next;
            node = node.next;
        }
        return ans;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值