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.
1 public class Solution { 2 public RandomListNode copyRandomList(RandomListNode head) { 3 //insert nodes 4 RandomListNode cur = head; 5 while(cur!=null){ 6 RandomListNode temp = new RandomListNode(cur.label); 7 temp.next = cur.next; 8 cur.next = temp; 9 cur = temp.next; 10 } 11 //copy random pointers 12 cur = head; 13 while(cur!=null){ 14 RandomListNode temp = cur.next; 15 if(cur.random!=null) 16 temp.random = cur.random.next; 17 cur = temp.next; 18 } 19 cur = head; 20 RandomListNode newHead = head==null?null:head.next; 21 while(cur!=null){ 22 RandomListNode temp = cur.next; 23 cur.next = temp.next; 24 if(temp.next!=null) 25 temp.next = temp.next.next; 26 cur = cur.next; 27 } 28 return newHead; 29 } 30 }
原文:http://www.cnblogs.com/krunning/p/3560673.html