- 复制每个节点,如:复制节点A得到A1,将A1插入到节点A后面;
- 遍历链表,A1.random = A.random.next;
- 将链表拆分成原链表和复制后的链表。
/*
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 pHead;
}
RandomListNode currNode = pHead;
while(currNode != null) {
RandomListNode cloneNode = new RandomListNode(currNode.label);
cloneNode.next = currNode.next;
currNode.next = cloneNode;
currNode = cloneNode.next;
}
currNode = pHead;
while(currNode != null) {
if(currNode.random != null){
currNode.next.random = currNode.random.next;
}
currNode = currNode.next.next;
}
currNode = pHead;
RandomListNode pCloneHead = pHead.next;
//注意这里的判断条件,当走到最后一个node的时候退出循环
//因为对于最后一个node有:currNode.next == null,所以无需对其进行操作
//而且如果进入循环后currNode.next = nextNode.next会出错
while(currNode.next != null) {
RandomListNode nextNode = currNode.next;
currNode.next = nextNode.next;
currNode = nextNode;
}
return pCloneHead;
}
}