码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Copy List with Random Pointer

时间:2016-03-16 14:03:12      阅读:161      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!