剑指offer.25.复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
代码实现
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 curNode = pHead;
while (curNode != null) {
RandomListNode cloneNode = new RandomListNode(curNode.label);
RandomListNode next = curNode.next;
curNode.next = cloneNode;
cloneNode.next = next;
curNode = next;
}
curNode = pHead;
while (curNode != null) {
curNode.next.random = curNode.random == null ? null : curNode.random.next;
curNode = curNode.next.next;
}
curNode = pHead;
RandomListNode pCloneHead = curNode.next;
while (curNode != null) {
RandomListNode cloneNode = curNode.next;
curNode.next = cloneNode.next;
curNode = cloneNode.next;
cloneNode.next = curNode == null ? null : curNode.next;
}
return pCloneHead;
}
}
分析
思路参考官方解答
链接:https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba?f=discussion
来源:牛客网
1.遍历链表,复制每一个结点,并插到被复制的结点后
2.每一个复制的结点的随机结点指向被复制结点的随机结点的下一个结点
3.拆分链表