Skip to content

Instantly share code, notes, and snippets.

@b27lu
Created February 24, 2014 16:28
Show Gist options
  • Save b27lu/9191597 to your computer and use it in GitHub Desktop.
Save b27lu/9191597 to your computer and use it in GitHub Desktop.
copy list with random pointer using HashMap
/**
* 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