lintcode-medium-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.

 

思路:

先按照正常顺序,得到复制的链表,同时用一个HashMap建立新旧节点的对应关系,再把random pointer加入,这样可以保证random pointer指向的节点永远都是已经建立的新节点,不会是null

/**
 * 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 {
    /**
     * @param head: The head of linked list with a random pointer.
     * @return: A new head of a deep copy of the list.
     */
    public RandomListNode copyRandomList(RandomListNode head) {
        // write your code here
        if(head == null)
            return null;
        
        RandomListNode newhead = new RandomListNode(head.label);
        RandomListNode p1 = head.next;
        RandomListNode p2 = newhead;
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        map.put(head, newhead);
        
        while(p1 != null){
            p2.next = new RandomListNode(p1.label);
            p2 = p2.next;
            map.put(p1, p2);
            p1 = p1.next;
        }
        
        p1 = head;
        p2 = newhead;
        
        while(p1 != null){
            p2.random = map.get(p1.random);
            p1 = p1.next;
            p2 = p2.next;
        }
        
        return newhead;
    }
}

 

posted @ 2016-03-16 13:26  哥布林工程师  阅读(128)  评论(0编辑  收藏  举报