脚本宝典收集整理的这篇文章主要介绍了leetcode刷题-剑指offer-35题,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
请实现 copyRandoMList
函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next
指针指向下一个节点,还有一个 random
指针指向链表中的任意节点或者 null
。
示例 1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例 4:
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。
新手上路,才学疏浅,望斧正
class Solution3 {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
//在每个节点后复制一份它自己
Node p = head;
while (p != null){
Node tem = new Node(p.val);
tem.next = p.next;
p.next = tem;
p = tem.next;
}
//复制ramdom 节点
p = head;
while (p != null){
if(p.random == null) {
p.next.random = null;
}else {
p.next.random = p.random.next;
}
p = p.next.next;
}
p = head;
Node res = null;
Node q=null;
while (p != null){
if(res == null){
res = p.next;
p.next = p.next.next;
q = res;
}else {
q.next = p.next;
p.next = p.next.next;
q = q.next;
}
p = p.next;
}
return res;
}
}
以上是脚本宝典为你收集整理的leetcode刷题-剑指offer-35题全部内容,希望文章能够帮你解决leetcode刷题-剑指offer-35题所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。