[Daily a small algorithm (fifty-one)] [list] complex chain of copy (to prove safety offer exercises)

Introduction:
the list of questions, the pointer must distinguish between good, not easy to be wrong.

Title Description

A complex input list (each node has a node value, and two pointers, one pointing to the next node, a special pointer to any other node), returns a value after the head of the list replication complex. (Note that the output results do not return parameter node reference, otherwise the program will return empty sentenced questions directly)

Problem-solving ideas

The questions, think for a long time have not thought out how to solve. Finally, the direct use of direct reproduction, using the mapping between the old map storage node and the new node. It can then use the existing node if the node already exists, if there is less need to open up new storage node and the mapping between them.

Sample Code

package com.asong.leetcode.CloneList;

import java.util.HashMap;

/**
 *  复杂链表的复制
 *  思路:使用map来存储映射关系。
 */
public class Solution1 {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead == null)
        {
            return null;
        }
        RandomListNode newHead = null;
        RandomListNode pPre = pHead;
        RandomListNode pClone = null;
        HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();
        while(pPre!=null)
        {
            if(newHead == null)
            {
                newHead = new RandomListNode(pPre.label);
                pClone = newHead;
                map.put(pHead,newHead);//保存映射关系
            }else {
                //先保存下一结点的值
                if (pPre.next!=null && map.containsKey(pPre.next))
                {
                    pClone.next = map.get(pPre.next);
                }else {
                    if(pPre.next!=null)
                    {
                        RandomListNode temp = new RandomListNode(pPre.next.label);
                        map.put(pPre.next,temp);
                        pClone.next = temp;
                    }
                }
                if(pPre.random!=null && map.containsKey(pPre.random))
                {
                    pClone.random = map.get(pPre.random);
                }else {
                    if(pPre.random!=null)
                    {
                        RandomListNode temp = new RandomListNode(pPre.random.label);
                        map.put(pPre.random,temp);
                        pClone.random = temp;
                    }
                }
                pPre = pPre.next;
                pClone = pClone.next;
            }
        }

        return newHead;
    }
}

Published 159 original articles · won praise 37 · views 4484

Guess you like

Origin blog.csdn.net/qq_39397165/article/details/104397632