138:复制带随机指针的链表

问题

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.

分析

第一遍遍历的时候仅仅是单纯的复制节点,把复制的节点放在hashMap中,第二遍遍历的时候,
将原来随机指针链表指向的赋给新的节点。

我的代码

/**
 * 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) {
        HashMap<RandomListNode,RandomListNode> hashMap=new HashMap();
        RandomListNode r1=head;
        RandomListNode r2=head;

        while(r1!=null){
            hashMap.put(r1,new  RandomListNode(r1.label));
            r1=r1.next;
        }

        while(r2!=null){
            hashMap.get(r2).next=hashMap.get(r2.next);
            hashMap.get(r2).random=hashMap.get(r2.random);
            r2=r2.next;
        }
        return hashMap.get(head);
    }
}