第一个是用了hashmap, 第二个是在每个结点后面加一个新的结点
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) { return head; } RandomListNode result = new RandomListNode(head.label); //copy next RandomListNode p1 = head; RandomListNode p2 = result; HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); map.put(p1, p2); while (p1.next != null) { p2.next = new RandomListNode(p1.next.label); p1 = p1.next; p2 = p2.next; map.put(p1, p2); } //copy random p1 = head; p2 = result; while (p1 != null) { p2.random = map.get(p1.random); p1 = p1.next; p2 = p2.next; } return result; } }
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) { return head; } RandomListNode p = head; while (p != null) { RandomListNode copy = new RandomListNode(p.label); copy.random = p.random; copy.next = p.next; p.next = copy; p = copy.next; } p = head.next; while (p != null) { if (p.random != null) p.random = p.random.next; if (p.next == null) { break; } p = p.next.next; } RandomListNode p1 = head; RandomListNode p2 = head.next; RandomListNode result = p2; while (p1 != null && p1.next != null) { p1.next = p1.next.next; if (p2.next != null) p2.next = p2.next.next; p1 = p1.next; p2 = p2.next; } return result; } }
[LeetCode]Copy List with Random Pointer
原文:http://www.cnblogs.com/vision-love-programming/p/5013239.html