leetcode138: Copy List with Random Pointer
来源:互联网 发布:淘宝的正品保证有用吗 编辑:程序博客网 时间:2024/06/11 09:01
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.
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; *///import java.util.HashMap;public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if(head==null) return null; //保存各节点random指针位置 HashMap<RandomListNode,RandomListNode> map=new HashMap<RandomListNode,RandomListNode>(); RandomListNode pp=head;//保存头结点 while(head!=null){ map.put(head, head.random); head=head.next; } //深度复制 head=pp;//回到头结点 RandomListNode p=head.next; RandomListNode pre=head;//用于连接链表, 先不管新链表的头节点的random指针,等到其他节点指针指好后,在考虑它。 RandomListNode one=pre;//保存新链表的头结点 while(p!=null){//从第二个节点开始复制,需要保留前一个指针,你懂的。 RandomListNode lnode=new RandomListNode(p.label); pre.next=lnode; lnode.next=null; lnode.random=map.get(p);//这块很重要,要知道从哪里获得random指针。 pre=lnode;//最终pre是最后一个节点 p=p.next; } one.random=map.get(head); return one; }}
0 0
- leetcode138: Copy List with Random Pointer
- LeetCode138—Copy List with Random Pointer
- leetcode138~Copy List with Random Pointer
- LeetCode138 Copy List with Random Pointer(深度复制带有随机指针的链表) Java题解
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Mysql中的LOCATE 和 SUBSTRING
- UITextView
- 合法括号序列判断
- java多线程-线程的实现
- python学习笔记-语法
- leetcode138: Copy List with Random Pointer
- Java中的继承
- 聊聊“尾递归优化“简介拷贝构造&拷贝赋值
- 分享一个牛逼的chrome插件--Postman
- Android学习之监听软键盘的弹起关闭
- android关于调用联系人信息的问题
- html 缓存公共数据数据 银行卡校验 身份证校验
- HDU4848WoW
- maven常见开发配置spring,hibernate,structs,jdbc,log4j,mybatis