Created
December 6, 2014 11:56
-
-
Save ericpony/4de4e2698c03db459abb to your computer and use it in GitHub Desktop.
Copy List with Random Pointer (with HashMap and n recursive calls)
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 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