标签:
原题链接在这里:https://leetcode.com/problems/copy-list-with-random-pointer/
每个node 带了一个random指针,问题就在于copy时也许这个random指针指向的还没有遍历到。一种直接的方法就是使用HashMap 做两遍itertion, 第一遍复制原有list包括next, 但是不复制random, 把original node 和 copy node 成对放到HashMap中,original node是键。第二遍遍历时把copy的random指向oringal node random 在HashMap中对应的点。
如此Time Complexity: O(n). Space O(n), 这种方法就不写了。
第二种方法不利用额外空间,那么只能利用原有数据结构。一共需要做三次iteration, 第一次遍历时对于每一个original node 做 copy然后放到original node的next里。第二次遍历时如果origianl的random不指向null, 就让它后面的copy node random 指向原有random指向点的next, cur.next.random = cur.random.next, 因为random指向点的next 就是指向点的copy.
第三次遍历时把原有list 拆成两个list, 一个原有list, 一个复制list.
Note: 做第二次遍历时要注意original random指向null的情况,因为后面用到了cur.random.next 若是指向null, 是没有next的。
AC Java:
1 /** 2 * Definition for singly-linked list with a random pointer. 3 * class RandomListNode { 4 * int label; 5 * RandomListNode next, random; 6 * RandomListNode(int x) { this.label = x; } 7 * }; 8 */ 9 public class Solution { 10 public RandomListNode copyRandomList(RandomListNode head) { 11 if(head == null){ 12 return head; 13 } 14 //First iteration, copy node and append it to the original node 15 RandomListNode cur = head; 16 while(cur != null){ 17 RandomListNode copy = new RandomListNode(cur.label); 18 copy.next = cur.next; 19 cur.next = copy; 20 cur = cur.next.next; 21 } 22 23 //Second iteration, if original random doesn‘t point to null, assign corresponding copy node random point to origianl 24 //random‘s next node 25 cur = head; 26 while(cur != null){ 27 if(cur.random != null){ 28 cur.next.random = cur.random.next; 29 } 30 cur = cur.next.next; 31 } 32 33 //Third iteration, separate list into two. One is origianl list, the other is the copy list. 34 cur = head; 35 RandomListNode copyHead = cur.next; 36 RandomListNode copyCur = copyHead; 37 cur.next = cur.next.next; 38 cur = cur.next; 39 while(cur != null){ 40 copyCur.next = cur.next; 41 copyCur = copyCur.next; 42 cur.next = cur.next.next; 43 cur = cur.next; 44 } 45 return copyHead; 46 } 47 }
LeetCode Copy List with Random Pointer
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4877096.html