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.
Return a deep copy of the list.
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 null; 13 } 14 copyNext(head); 15 copyRandom(head); 16 RandomListNode newHead = splitList(head); 17 return newHead; 18 } 19 20 private void copyNext(RandomListNode head) { 21 while(head != null) { 22 RandomListNode copy = new RandomListNode(head.label); 23 copy.next = head.next; 24 head.next = copy; 25 head = head.next.next; 26 } 27 } 28 29 private void copyRandom(RandomListNode head) { 30 while (head != null) { 31 if (head.random != null) { 32 head.next.random = head.random.next; 33 } 34 head = head.next.next; 35 } 36 } 37 38 private RandomListNode splitList(RandomListNode head) { 39 RandomListNode newHead = head.next; 40 while (head != null) { 41 RandomListNode temp = head.next; 42 head.next = temp.next; 43 head = head.next; 44 if (temp.next != null) { 45 temp.next = temp.next.next; 46 } 47 } 48 return newHead; 49 } 50 }
原文:http://www.cnblogs.com/FLAGyuri/p/5652241.html