leetcode刷题-剑指offer-35题
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。
解答
新手上路,才学疏浅,望斧正
- 先复制节点,再复制节点中的random
- 先把每个节点(假设为A)复制一份,放在它的后面(假设为 A1 )。
- 再 复制random 即A1的random 为 A的random(假设为B)的后一个节点(假设为B1)
- 将新节点(A1 , B1 ,,,)拆出来即可
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;
}
}
本文作者:发呆鱼
本文链接:https://www.cnblogs.com/dyiblog/p/15778620.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步