考點:分解讓複雜問題簡單java
https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba?f=discussiondom
/*
*解題思路:
*
1
、遍歷鏈表,複製每一個結點,如複製結點A獲得A1,將結點A1插到結點A後面;
*
2
、從新遍歷鏈表,複製老結點的隨機指針給新結點,如A1.random = A.random.next;
*
3
、拆分鏈表,將鏈表拆分爲原鏈表和複製後的鏈表
*/
/* public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } */ public class Solution { public RandomListNode Clone(RandomListNode pHead) { if(pHead == null) { return null; } RandomListNode currentNode = pHead; //一、複製每一個結點,如複製結點A獲得A1,將結點A1插到結點A後面; while(currentNode != null){ RandomListNode cloneNode = new RandomListNode(currentNode.label); RandomListNode nextNode = currentNode.next; currentNode.next = cloneNode; cloneNode.next = nextNode; currentNode = nextNode; } currentNode = pHead; //二、從新遍歷鏈表,複製老結點的隨機指針給新結點,如A1.random = A.random.next; while(currentNode != null) { currentNode.next.random = currentNode.random==null?null:currentNode.random.next; currentNode = currentNode.next.next; } //三、拆分鏈表,將鏈表拆分爲原鏈表和複製後的鏈表 currentNode = pHead; RandomListNode pCloneHead = pHead.next; while(currentNode != null) { RandomListNode cloneNode = currentNode.next; currentNode.next = cloneNode.next; cloneNode.next = cloneNode.next==null?null:cloneNode.next.next; currentNode = currentNode.next; } return pCloneHead; } }