138 Copy List with Random Pointer 复制带随机指针的链表

给出一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
返回一个深拷贝的链表。
详见:https://leetcode.com/problems/copy-list-with-random-pointer/description/

Java实现:

/**
 * 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 cur=head;
        Map<RandomListNode,RandomListNode> m=new HashMap<RandomListNode,RandomListNode>();
        while(cur!=null){
            m.put(cur,new RandomListNode(cur.label));
            cur=cur.next;
        }
        cur=head;
        while(cur!=null){
            m.get(cur).next=m.get(cur.next);
            m.get(cur).random=m.get(cur.random);
            cur=cur.next;
        }
        return m.get(head);
    }
}
原文地址:https://www.cnblogs.com/xidian2014/p/8724769.html