Created
February 24, 2014 16:28
-
-
Save b27lu/9191597 to your computer and use it in GitHub Desktop.
copy list with random pointer using HashMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 head; | |
HashMap<RandomListNode, RandomListNode> hm = new HashMap<RandomListNode, RandomListNode>(); | |
RandomListNode current = head; | |
while(current != null){ | |
hm.put(current, new RandomListNode(current.label)); | |
current = current.next; | |
} | |
current = head; | |
while(current != null){ | |
hm.get(current).next = hm.get(current.next); | |
hm.get(current).random = hm.get(current.random); | |
current = current.next; | |
} | |
return hm.get(head); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment