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

[LeetCode]138 Copy List with Random Pointer

时间:2015-01-08 18:15:38      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/copy-list-with-random-pointer/

http://blog.csdn.net/linhuanmars/article/details/22463599

/**
 * 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;
        
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        RandomListNode old = head;
        RandomListNode precopied = null;
        while (old != null)
        {
            // Copy
            RandomListNode copied = new RandomListNode(old.label);
            if (precopied != null)
                precopied.next = copied;
            precopied = copied;
            map.put(old, copied);
            
            old = old.next;
        }
        
        RandomListNode newhead = map.get(head);
        while (head != null)
        {
            map.get(head).random = map.get(head.random);
            head = head.next;
        }
        
        return newhead;
    }    
}


[LeetCode]138 Copy List with Random Pointer

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1600774

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!