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.

  • 思路
    由于有了一个随机的指针,因此这个单向链表有点像图,思路跟克隆一个图很相近,使用一个字典集合保存已经克隆的节点(key为被克隆节点的hash值,值为已克隆节点),使用递归进行克隆,每次克隆前判断是否该节点已经克隆,如果已经克隆,则取出该节点。
  • 代码(c#)
  public RandomListNode CopyRandomList(RandomListNode head)
        {
            Dictionary<int, RandomListNode> dictionary = new Dictionary<int, RandomListNode>();//保存已经克隆的节点
            return CopyRandomList(head, dictionary);
        }
        public RandomListNode CopyRandomList(RandomListNode head, Dictionary<int, RandomListNode> dictionary)
        {
            if (head == null) return head;
            int key = head.GetHashCode();
            RandomListNode randomListNode = CopyOne(head,dictionary);//创建或取出已经克隆的节点
            if (head.random != null)
            {
                randomListNode.random = CopyOne(head.random, dictionary);//创建或取出已经克隆的节点
            }
            randomListNode.next = CopyRandomList(head.next, dictionary);//克隆下一个节点
            return randomListNode;
        }
        public RandomListNode CopyOne(RandomListNode head, Dictionary<int, RandomListNode> dictionary)
        {
            int key = head.GetHashCode();
            RandomListNode randomListNode = null;
            if (dictionary.ContainsKey(key))
            {
                randomListNode = dictionary[key];
            }
            else
            {
                randomListNode = new RandomListNode(head.label);
                dictionary[key] = randomListNode;
            }
            return randomListNode;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值