Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active January 3, 2016 11:09
Show Gist options
  • Save junjiah/8454501 to your computer and use it in GitHub Desktop.
Save junjiah/8454501 to your computer and use it in GitHub Desktop.
solved "Copy List with Random Pointer" on LeetCode (one-pass AC! reminds me of copying GC) http://oj.leetcode.com/problems/copy-list-with-random-pointer/
/**
* 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;
RandomListNode iter = head;
RandomListNode newHead = new RandomListNode(head.label);
RandomListNode newIter = newHead;
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
// first pass, copy object
do {
map.put(iter, newIter);
iter = iter.next;
if (iter != null)
newIter.next = new RandomListNode(iter.label);
newIter = newIter.next;
} while (iter != null);
iter = head;
newIter = newHead;
// second pass, modify random pointer
while (iter != null) {
if (iter.random != null)
newIter.random = map.get(iter.random);
iter = iter.next;
newIter = newIter.next;
}
return newHead;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment