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.
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; */ publicclassSolution { public RandomListNode copyRandomList(RandomListNode head) { RandomListNoderesult=newRandomListNode(0); if(head == null) returnnull;
// Use a hashmap to store the mapping Map<RandomListNode, RandomListNode> oldToNew = newHashMap<RandomListNode, RandomListNode>();
RandomListNodecursor= head; // create new nodes for new list while(cursor != null) { RandomListNodetmp=newRandomListNode(cursor.label); oldToNew.put(cursor, tmp); cursor = cursor.next; }