Question:
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.
Answer:
/**
* 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 null;
HashMap<RandomListNode,RandomListNode> hmap = new HashMap<RandomListNode, RandomListNode>();
RandomListNode newListHead = new RandomListNode(head.label);
hmap.put(head, newListHead);
RandomListNode prevNew = newListHead, curOld = head.next, curNew=null;
while(curOld!= null){ //copy label and next
curNew = new RandomListNode(curOld.label);
hmap.put(curOld,curNew);
prevNew.next = curNew;
prevNew = curNew;
curOld = curOld.next;
}
prevNew.next = null;
curOld = head; curNew = newListHead;
while(curOld!= null){ //copy random
curNew.random = hmap.get(curOld.random);
curOld = curOld.next;
curNew = curNew.next;
}
return newListHead;
}
}
No comments:
Post a Comment