首页 > 其他 > 详细

lintcode-medium-Copy List with Random Pointer

时间:2016-03-16 13:59:57      阅读:239      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

lintcode-medium-Copy List with Random Pointer

原文:http://www.cnblogs.com/goblinengineer/p/5283105.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!