1 /* 2 public class RandomListNode { 3 int label; 4 RandomListNode next = null; 5 RandomListNode random = null; 6 7 RandomListNode(int label) { 8 this.label = label; 9 } 10 } 11 */ 12 /* 13 1.在舊鏈表中建立新的鏈表,此時不處理新鏈表的兄弟鏈表 14 2.根據舊鏈表的兄弟結點,初始化新鏈表中的兄弟結點 15 3.從舊鏈表中拆分獲得新鏈表 16 */ 17 public class Solution { 18 public RandomListNode Clone(RandomListNode pHead) 19 { 20 if (pHead==null) 21 return null; 22 RandomListNode currentNode = pHead; 23 //複製每一個結點,並將複製後的結點插入結點以後 24 while(currentNode != null){ 25 RandomListNode cloneNode = new RandomListNode(currentNode.label); 26 RandomListNode nextNode = currentNode.next; 27 currentNode.next = cloneNode; 28 cloneNode.next = nextNode; 29 currentNode = nextNode; 30 } 31 currentNode = pHead; 32 //從新遍歷鏈表,複製老結點的隨機指針給新結點 33 while(currentNode != null){ 34 currentNode.next.random = currentNode.random==null?null:currentNode.random.next; 35 currentNode = currentNode.next.next; 36 } 37 //拆分鏈表,將鏈表拆分爲原鏈表和複製後的鏈表 38 currentNode = pHead; 39 RandomListNode pCloneHead = pHead.next; 40 while(currentNode!=null){ 41 RandomListNode cloneNode = currentNode.next; 42 currentNode.next = cloneNode.next; 43 cloneNode.next = cloneNode.next == null?null:cloneNode.next.next; 44 currentNode = currentNode.next; 45 } 46 return pCloneHead; 47 } 48 }