LeetCode – Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
1 /** 2 * Definition for singly-linked list with a random pointer. 3 * class RandomListNode { 4 * int label; 5 * RandomListNode next, random; 6 * RandomListNode(int x) { this.label = x; } 7 * }; 8 */ 9 public class Solution { 10 public RandomListNode copyRandomList(RandomListNode head) { 11 if(head==null) 12 return null; 13 RandomListNode p=head;
//拷贝当前节点,并将其插入到被拷贝节点的后方 14 while(p!=null){ 15 RandomListNode temp=new RandomListNode(p.label); 16 temp.next=p.next; 17 p.next=temp; 18 p=temp.next; 19 } 20 p=head;
//将拷贝节点的随机指针指向应有位置 21 while(p!=null){ 22 if(p.random!=null){ 23 p.next.random=p.random.next; 24 } 25 p=p.next.next; 26 } 27 RandomListNode newhead=head.next; 28 p=head;
//将拷贝链表与原链表分离 29 while(p!=null){ 30 RandomListNode temp=p.next; 31 p.next=temp.next; 32 if(temp.next!=null) 33 temp.next=temp.next.next; 34 p=p.next; 35 } 36 return newhead; 37 } 38 }
最后分离也可这样写:
1 while(p != null && p.next != null){ 2 RandomListNode temp = p.next; 3 p.next = temp.next; 4 p = temp; 5 }
解法2:
可以用hashmap的方式
1 public RandomListNode copyRandomList(RandomListNode head) { 2 if (head == null) 3 return null; 4 HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); 5 RandomListNode newHead = new RandomListNode(head.label); 6 7 RandomListNode p = head; 8 RandomListNode q = newHead; 9 map.put(head, newHead); 10 11 p = p.next; 12 while (p != null) { 13 RandomListNode temp = new RandomListNode(p.label); 14 map.put(p, temp); 15 q.next = temp; 16 q = temp; 17 p = p.next; 18 } 19 20 p = head; 21 q = newHead; 22 while (p != null) { 23 if (p.random != null) 24 q.random = map.get(p.random); 25 else 26 q.random = null; 27 28 p = p.next; 29 q = q.next; 30 } 31 32 return newHead; 33 }
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-01-12 ubuntu14.04无法连接有线连接问题
2016-01-12 ANDROID颜色设置
2016-01-12 android 从Activity 获取 rootView 根节点
2016-01-12 获取当前View
2016-01-12 Cannot make a static reference to the non-static method的解决方法
2016-01-12 Android 不同View ID相同
2016-01-12 WindowManager.LayoutParams全解