Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active March 16, 2016 14:14
Show Gist options
  • Save cangoal/d3e2b42c1755f6706224 to your computer and use it in GitHub Desktop.
Save cangoal/d3e2b42c1755f6706224 to your computer and use it in GitHub Desktop.
LeetCode - Copy List with Random Pointer
// use hashmap
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null) return head;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode cur = head;
while(cur != null){
RandomListNode newNode = new RandomListNode(cur.label);
map.put(cur, newNode);
cur = cur.next;
}
for(Map.Entry<RandomListNode, RandomListNode> entry : map.entrySet()){
RandomListNode node = entry.getKey();
RandomListNode copyNode = entry.getValue();
copyNode.next = map.get(node.next);
copyNode.random = map.get(node.random);
}
return map.get(head);
}
// use hashmap
public RandomListNode copyRandomList(RandomListNode head) {
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode p = head;
RandomListNode dummy = new RandomListNode(0);
RandomListNode q = dummy;
while(p != null){
q.next = new RandomListNode(p.label);
map.put(p, q.next);
p = p.next;
q = q.next;
}
p = head;
q = dummy;
while(p != null){
q.next.random = map.get(p.random);
p = p.next;
q = q.next;
}
return dummy.next;
}
// constant space complexity
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null) return null;
RandomListNode p = head;
while(p != null){
RandomListNode newNode = new RandomListNode(p.label);
RandomListNode next = p.next;
p.next = newNode;
newNode.next = next;
p = next;
}
p = head;
while(p != null){
p.next.random = (p.random != null) ? p.random.next : null;
p = p.next.next;
}
p = head;
RandomListNode dummy = new RandomListNode(0);
RandomListNode pre = dummy;
while(p != null){
RandomListNode next = p.next.next;
pre.next = p.next;
pre = pre.next;
p.next = next;
p = p.next;
}
return dummy.next;
}
// use hashmap
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null) return null;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode dummy = new RandomListNode(0);
RandomListNode pre = dummy;
RandomListNode q = head;
while(head!=null){
RandomListNode newNode = new RandomListNode(head.label);
map.put(head, newNode);
pre.next = newNode;
pre = pre.next;
head = head.next;
}
RandomListNode newhead = dummy.next;
while(q != null){
newhead.random = map.get(q.random);
newhead = newhead.next;
q = q.next;
}
return dummy.next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment