copy-list-with-random-pointer Java code

来源:互联网 发布:2018网络剧上映时间表 编辑:程序博客网 时间:2024/06/07 14:58

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.

/** * Definition for singly-linked list with a random pointer. * class RandomListNode { *     int label; *     RandomListNode next, random; *     RandomListNode(int x) { this.label = x; } * }; */import java.util.*;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;    }}
原创粉丝点击