思路:比如说原链表是ABCD。则先复制结点A' B' C' D',分别连接在ABCD后面。然后遍历ABCD,得知每个原结点的random指向。那么复制结点的random指向原结点random的后一个。(A---C,则A'----C后面的C') 再次遍历链表,将所有原结点跨个相连,将复制结点跨个相连。返回复制结点的第一个即可。
/*
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;CloneNode(pHead);CloneRandom(pHead);return SeperateListNode(pHead);}public void CloneNode(RandomListNode pHead){RandomListNode cNode = null;while(pHead != null){cNode = new RandomListNode(pHead.label);cNode.next = pHead.next;pHead.next = cNode;pHead = pHead.next.next;}}public void CloneRandom(RandomListNode pHead){RandomListNode cNode = null;while(pHead != null){cNode = pHead.next;if(pHead.random != null){cNode.random = pHead.random.next;}pHead = cNode.next;}}public RandomListNode SeperateListNode(RandomListNode pHead){RandomListNode result = pHead.next;while(pHead != null && pHead.next != null){RandomListNode cCurr = pHead.next;if(pHead.next != null){pHead.next = pHead.next.next;}if(cCurr != null && cCurr.next != null){cCurr.next = cCurr.next.next;}pHead = pHead.next;cCurr = cCurr.next;}return result;}
}