Skip to content

Instantly share code, notes, and snippets.

@ericpony
Created December 6, 2014 11:56
Show Gist options
  • Save ericpony/4de4e2698c03db459abb to your computer and use it in GitHub Desktop.
Save ericpony/4de4e2698c03db459abb to your computer and use it in GitHub Desktop.
Copy List with Random Pointer (with HashMap and n recursive calls)
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class RecursiveVersion {
public RandomListNode copyRandomList(RandomListNode head) {
HashMap<RandomListNode,RandomListNode> nodes = new HashMap<RandomListNode,RandomListNode>();
return copyListHelper(head, nodes);
}
public RandomListNode copyListHelper(RandomListNode head, HashMap<RandomListNode,RandomListNode> nodes) {
if(head==null) return null;
if(nodes.containsKey(head)) return nodes.get(head);
RandomListNode ret = new RandomListNode(head.label);
nodes.put(head,ret);
ret.next = copyListHelper(head.next, nodes);
ret.random = copyListHelper(head.random,nodes);
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment