输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
第一步,在每个节点的后面插入复制的节点。
第二步,对复制节点的 random 链接进行赋值。
第三步,拆分。
public class RandomListNodeClone {
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null)
return null;
// 插入新节点
RandomListNode cur = pHead;
while (cur != null) {
//创建新节点
RandomListNode clone = new RandomListNode(cur.label);
//新节点的后继指向当前节点的后继
clone.next = cur.next;
//当前节点的后继指向新节点
cur.next = clone;
//当前节点指向之前自己的后继节点
cur = clone.next;
}
// 建立 random 链接
cur = pHead;
while (cur != null) {
RandomListNode clone = cur.next;
if (cur.random != null)
//让克隆节点的random后继指向自己random的后继,也就是复制版的后继节点
clone.random = cur.random.next;
//当前节点指针指向下一个非克隆节点(因为clone和非clone是相间的)
cur = clone.next;
}
// 拆分
cur = pHead;
RandomListNode pCloneHead = pHead.next;
while (cur.next != null) {
//原始节点的后继节点是克隆节点,克隆节点的后继节点是原始节点
RandomListNode next = cur.next;
//当前节点的后继指向后继节点的后继(也就是原来自己的后继,因为clone和非clone是相间的)
cur.next = next.next;
//当前指向往后挪
cur = next;
}
return pCloneHead;
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有