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

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
 
 /* 
   create a hashmap store <oldNode, newNode>
   copy value and next to new list
   copy random node in hashmap for new list
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null) return null;
        RandomListNode newhead = new RandomListNode(head.label);
        RandomListNode newl = newhead;
        RandomListNode oldl = head.next;
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        map.put(head, newhead);
        while(oldl != null){
            RandomListNode newNode = new RandomListNode(oldl.label);
            map.put(oldl, newNode);
            newl.next = newNode;
            
            oldl = oldl.next;
            newl = newl.next;
        }
        
        oldl = head;
        newl = newhead;
        while(oldl != null){
            newl.random = map.get(oldl.random);
            
            newl = newl.next;
            oldl = oldl.next;
        }
        return newhead;
    }
}

 

posted @ 2016-11-28 11:13  微微程序媛  阅读(118)  评论(0编辑  收藏  举报