如果直接复制然后遍历每一个结点的随机指针,那样时间复杂度为O(n²)。
所以思路为:
- 复制链表:直接在原链表复制新的链表然后把新链表的每一个结点插入原结点的下一结点;
- 复制指针:重新遍历链表,复制老结点的指针到新的结点上;
- 拆分链表:将当前链表拆分为原链表和复制后的链表。
如图所示:
/*
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;
//复制原链表每一个节点,并插入其下一个节点
while(currentNode != null){
RandomListNode cloneNode = new RandomListNode(currentNode.label);
RandomListNode nextNode = currentNode.next;
currentNode.next = cloneNode;
cloneNode.next = nextNode;
currentNode = nextNode;
}
currentNode = pHead;
//重新遍历链表,复制老结点的随机指针给新结点
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;
}
}
.next思路有点混乱
currentNode.label 不懂啥意思
RandomListNode currentNode = pHead
currentNode = pHead