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.
2016-05-19 09:27
549 查看
图解:
此题过程分为三个阶段,分别是 1、负责后面一个节点,并且将这个节点插入到原来链表中 2、复制后面一个节点的random指针。 3 拆分组合链表为两部分。
第一部分代码:
第二部分 代码:
第三部分代码:
总的代码:
此题过程分为三个阶段,分别是 1、负责后面一个节点,并且将这个节点插入到原来链表中 2、复制后面一个节点的random指针。 3 拆分组合链表为两部分。
第一部分代码:
while(currentnode!=null){//复制节点,并且将节点插入到该节点的后面 RandomListNode clonenode=new RandomListNode(currentnode.label); clonenode.next=currentnode.next; currentnode.next=clonenode; currentnode=clonenode.next; }
第二部分 代码:
currentnode=head; while(currentnode!=null){//复制随机指针。 RandomListNode clonenode=currentnode.next; if(currentnode.random!=null){ clonenode.random=currentnode.random.next;//这里要指向随机指针的后一个,因为是复制滴啊,千万不要忘记了。 } currentnode=clonenode.next; }
第三部分代码:
RandomListNode cloneHead=head.next; currentnode=head; while(currentnode.next!=null){ RandomListNode temp=currentnode.next; currentnode.next=temp.next; currentnode=temp; }
总的代码:
class RandomListNode { int label; RandomListNode next, random; RandomListNode(int x) { this.label = x; } }; public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if(head==null)return null; RandomListNode currentnode=head; while(currentnode!=null){//复制节点,并且将节点插入到该节点的后面 RandomListNode clonenode=new RandomListNode(currentnode.label); clonenode.next=currentnode.next; currentnode.next=clonenode; currentnode=clonenode.next; } currentnode=head; while(currentnode!=null){//复制随机指针。 RandomListNode clonenode=currentnode.next; if(currentnode.random!=null){ clonenode.random=currentnode.random.next;//这里要指向随机指针的后一个,因为是复制滴啊,千万不要忘记了。 } currentnode=clonenode.next; } RandomListNode cloneHead=head.next; currentnode=head; while(currentnode.next!=null){ RandomListNode temp=currentnode.next; currentnode.next=temp.next; currentnode=temp; } return cloneHead; } }
相关文章推荐
- 三步将Node应用部署到Heroku上
- 【NodeJS】运行在服务端的JavaScript
- LeetCode 24. Swap Nodes in Pairs(交换节点)
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- Node.js+Express配置入门教程详解
- nodejs ENOSPC
- hadoop SecondNamenode详解
- 【软件】IDEA web项目里包含node_modules 一直处于make状态
- DOMNodeRemoved事件 删除元素之后触发的事件
- 利用heroku+mongoLab 部署Node 运用
- Node
- node.js 安装和 配置Sublime Text2的Nodejs
- childNodes和Children的区别
- nodejs window下安装与配置淘宝镜像
- 配置 Sublime Text 开发node.js和js-beautify-sublime(代码格式化)
- Node.js EventEmitter事件发射器
- node-webkit:开发桌面+WEB混合型应用的神器
- Node.js刷新session过期时间的实现方法推荐
- 【leetcode】237. Delete Node in a Linked List
- 关于nodejs iconv的编码无效 说明