leetcode:Copy List with Random Pointer 细致分析,以及代码实现(JAVA版本)
来源:互联网 发布:大数据工资一般多少 编辑:程序博客网 时间:2024/06/06 08:43
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.
Subscribe to see which companies asked this question
题目分析:深度复制链表,既要复制next,又要复制random,next好复制,random要怎么处理呢,考虑到我们只知道链表的下一个节点是什么。那我们就在链表之后插入复制的节点,之后再进行调整。
可以分为3步:
1.在每个节点后插入复制的节点
2.复制random
3. 分离两条链表
具体代码如下:
public RandomListNode copyRandomList(RandomListNode head) { if(head==null) return null; RandomListNode newhead=null; RandomListNode now=head; // 第一步在当前节点之后,插入赋值节点 while(now!=null) { RandomListNode copy=new RandomListNode(now.label); copy.next=now.next; now.next=copy; now=now.next.next; } //第二步,拷贝RandomNode now=head; while(now!=null) { if(now.random!=null) now.next.random=now.random.next; now=now.next.next; } //第三步,还原两条链表 now=head; newhead=now.next; RandomListNode p=newhead; while(now!=null) { now.next=now.next.next; //当之后没有节点时,p.next=null。需要进行非空判断 if(p.next!=null) p.next=p.next.next; now=now.next; p=p.next; } return newhead; }
0 0
- leetcode:Copy List with Random Pointer 细致分析,以及代码实现(JAVA版本)
- [Leetcode] Copy List with Random Pointer (Java)
- [leetcode] Copy List with Random Pointer, Java
- Copy List with random pointer--Leetcode(Java)
- Copy List with Random Pointer leetcode java
- [leetcode][list] Copy List with Random Pointer
- LeetCode Copy List with Random Pointer 分析解答
- Leetcode: Copy List With Random Pointer分析理解
- [leetcode-138]Copy List with Random Pointer(java)
- [LeetCode] 138. Copy List with Random Pointer java
- [leetcode]138. Copy List with Random Pointer@Java解题报告
- Leetcode: Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- 银行卡号4位分隔JS
- 古人和眼镜
- Java读取Excel中的数据
- Java读取有输出文件
- 自用Sublime设置
- leetcode:Copy List with Random Pointer 细致分析,以及代码实现(JAVA版本)
- 删除数组中重复的值
- 关于在自定义初始化方法里给text赋值失败的解决
- 张家界自助游攻略
- Shell简易程序判断某个日期是星期几
- 【Proguard】Proguard混淆时保留行号信息
- iOS Crash文件的解析
- Kafka的副本策略——《Learning Apache Kafka》学习笔记(原书第三章第4节)
- Android开发,系统通讯录功能开发扩展资料汇总