Copy List with Random Pointer

来源:互联网 发布:微信检测僵尸粉源码 编辑:程序博客网 时间:2024/05/17 01:23

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; } * }; */public class Solution {    public RandomListNode copyRandomList(RandomListNode head) {        if(head == null) {            return head;        }                HashMap<RandomListNode, RandomListNode> map             = new HashMap<RandomListNode, RandomListNode>();        RandomListNode p = head;        while(p != null) {            RandomListNode node = new RandomListNode(p.label);            map.put(p, node);            p = p.next;        }                p = head;        while(p != null) {            RandomListNode matchNode = map.get(p);            matchNode.next = null;            matchNode.random = null;                        if(p.next != null) {                matchNode.next = map.get(p.next);            }            if(p.random != null) {                matchNode.random = map.get(p.random);            }            p = p.next;        }                return map.get(head);    }}


0 0