标签:
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 copyList(head); 15 copyRandom(head); 16 return splitList(head); 17 } 18 19 private void copyList(RandomListNode head) { 20 while (head != null) { 21 RandomListNode newNode = new RandomListNode(head.label); 22 newNode.random = head.random; 23 newNode.next = head.next; 24 head.next = newNode; 25 head = head.next.next; 26 } 27 } 28 29 private void copyRandom(RandomListNode head) { 30 while (head != null) { 31 if (head.next.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 if (temp.next != null) { 44 temp.next = temp.next.next; 45 } 46 head = head.next; 47 } 48 return newHead; 49 } 50 }
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5778736.html