Easy to understand use Dictionary (C#)


  • 0
    M
    public RandomListNode CopyRandomList(RandomListNode head)
                {
                    if (head == null)
                        return null;
                    Dictionary<RandomListNode, RandomListNode> set = new Dictionary<RandomListNode, RandomListNode>();
                    RandomListNode newHead = new RandomListNode(head.label);
                    set.Add(head, newHead);
                    RandomListNode current = newHead;
                    while (head != null)
                    {
                        //random
                        if(head.random!=null)
                        {
                            if (set.ContainsKey(head.random))
                                newHead.random = set[head.random];
                            else
                            {
                                RandomListNode ra = new RandomListNode(head.random.label);
                                set.Add(head.random, ra);
                                newHead.random = ra;
                            }
                        }
                        //next
                        if (head.next != null)
                        {
                            if (set.ContainsKey(head.next))
                            {
                                newHead.next = set[head.next];
                            }
                            else
                            {
                                newHead.next = new RandomListNode(head.next.label);
                                set.Add(head.next, newHead.next);
                            }
                        }
                        head = head.next;
                        newHead = newHead.next;
                    }
                    return current;
                }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.