首页 > 编程语言 > 详细

Java for LeetCode 138 Copy List with Random Pointer

时间:2015-06-03 17:26:38      阅读:203      评论: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.

解题思路:

我们在Java for LeetCode 133 Clone Graph题中做过图的复制,本题和图的复制十分类似,JAVA实现如下:

    public RandomListNode copyRandomList(RandomListNode head) {
		if (head == null)
			return null;
		HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
		RandomListNode node = new RandomListNode(head.label);
		RandomListNode headTemp = head, nodeTemp = node;
		map.put(head, node);
		while (headTemp.next != null) {
			nodeTemp.next = new RandomListNode(headTemp.next.label);
			map.put(headTemp.next, nodeTemp.next);
			headTemp = headTemp.next;
			nodeTemp = nodeTemp.next;
		}
		headTemp = head;
		nodeTemp = node;
		while (headTemp!= null) {
			if(map.containsKey(headTemp.random))
				nodeTemp.random=map.get(headTemp.random);
			headTemp = headTemp.next;
			nodeTemp = nodeTemp.next;
		}
		return node;
    }

 

Java for LeetCode 138 Copy List with Random Pointer

原文:http://www.cnblogs.com/tonyluis/p/4549536.html

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