LeetCode-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.

import java.util.*;
/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)
            return null;
        RandomListNode pNode = head, copyHead = null, copyNode = null;
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        while(pNode != null){
            RandomListNode node = new RandomListNode(pNode.label);
            node.next = null;
            node.random = null;
             
            if(pNode == head){
                copyHead = copyNode = node;
            }
            else{
                copyNode.next = node;
                copyNode = copyNode.next;
            }
            map.put(pNode, copyNode);
            pNode = pNode.next;
        }
        for(Map.Entry<RandomListNode, RandomListNode> m: map.entrySet()){
            m.getValue().random = map.get(m.getKey().random);
        }
        return copyHead;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/88565822