输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
分析:
注意,原来的链表也要分离出来,虽然不是题目要求,但是既然是复制,肯定是要额外的一条链表,不能破坏原来链表。
AC代码:
/*
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 p = pHead;
while (p != null) {
RandomListNode node = new RandomListNode(p.label);
node.next = p.next;
p.next = node;
p = node.next;
}
p = pHead.next;
RandomListNode last = pHead;
while (p != null) { // 可能random指向自己,或者一个不在链表中的结点
p.random = last.random == null ? null : last.random.next;
last = p.next;
p = last == null ? null : last.next;
}
RandomListNode curHead = pHead.next;
last = pHead;
p = curHead;
while (p!= null) {
last.next = p.next;
last = p.next;
p.next = last == null ? null : last.next;
p = p.next;
}
return curHead;
}
}
测试点可能为{1,2,3,4,5,3,5,#,2,#} ,#代表null,链表可能1-2-3-4-5-3-5,#,2,#,这3个结点可能是非链表结点,但是是random指向的结点。
扫码关注腾讯云开发者
领取腾讯云代金券
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. 腾讯云 版权所有